Copy Stack to Array

This is a version of the algorithm I have:

public void copyStackToArray(Stack<Integer> stack) {
    int i = 0;
    while (!this.bestRouteStack.empty()) {
        this.array[i++] = stack.pop();
    }
}

(the bounds on the array are guaranteed to be okay here for my code)

I'm wondering if there is a library algorithm that does this, but a search turned up nothing.

4

2 Answers

Stack subclasses Vector which already supports this, try this...

stack.toArray(array)

Here is the Javadoc for this.

1

I found that when I used the toArray method, I got the results in the reverse order to what I expected. When I created this stack:

Stack<String> stack = new Stack<>();
stack.push("foo");
stack.push("bar");

I wanted an array like:

{"bar", "foo"}

Because of course, stacks are LIFO. If you pop each element off the stack, you would pop "bar" first, and then "foo".

Instead, toArray returns {"foo", "bar"}.

A solution is to use a LinkedList instead. There is a push method on LinkedList, it performs the same as addFirst, and the result will be a list whose contents (if you traverse it of course) are "bar" and then "foo". And it also has the toArray method which returns as expected.


Test case:

LinkedList<String> list = new LinkedList<>();
list.push("foo");
list.push("bar");
String[] arr = list.toArray(new String[0]);
Assert.assertArrayEquals(new String[] { "bar", "foo" }, arr);
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest