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);
Stackyour own implementation or Java's?java.util.StacktoArray()method.toArray(T[] a)already does