As Stack is a Collection it implements the toArray(T[]) method so that you can use this to convert your stack to an array and use the solution to your working array.
However, you will have a problem that there is no autoboxing for arrays. Autoboxing automatically converts between primitive types and objects, which means, for example, that you can add int values directly to your Stack without creating Integer objects, since the compiler does this for you:
Stack<Integer> stack = new Stack<Integer>(); stack.push(20); stack.push(53);
However, the compiler will not convert between int[] and Integer[] , so you will need to:
Integer[] array = stack.toArray(new Integer[stack.size()]);
And using Integer[] would be a chorus.
So, the easiest way to do this is:
int[] array = new int[stack.size()]; for (int i = 0; i < array.length; i++) { array[i] = stack.get(i); }
Creating an array once will be more efficient than re-cloning and emptying the stack.
(Although if this is a homework question designed to teach you how to use stacks, this might not be the best approach!)
source share