5

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
  • Is Stack your own implementation or Java's? Commented Jan 6, 2014 at 21:25
  • Java's java.util.Stack Commented Jan 6, 2014 at 21:25
  • 10
    Check out its overloaded toArray() method. Commented Jan 6, 2014 at 21:26
  • toArray(T[] a) already does Commented Jan 6, 2014 at 21:26

2 Answers 2

8

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

stack.toArray(array)

Here is the Javadoc for this.

Sign up to request clarification or add additional context in comments.

1 Comment

It's actually inherited from java.util.Vector, not List (your link even goes to the Vector docs).
3

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 Comment

Thanks for this insight. This bit me when I was converting a codebase from using Stack to LinkedList. The API is almost identical but the code relied on toArray(), which now returned the reverse of what was expected.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.