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.
2 Answers
Stack subclasses Vector which already supports this, try this...
stack.toArray(array)
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);