user473973
user473973

Reputation: 711

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.

Upvotes: 5

Views: 19598

Answers (2)

Ricket
Ricket

Reputation: 34085

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);

Upvotes: 3

Todd
Todd

Reputation: 31720

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

stack.toArray(array)

Here is the Javadoc for this.

Upvotes: 8

Related Questions