I'm looking for a proper way to copy java.util.Stack in Java.
Stack doesn't seem to have a copy constructor, and the only thing I have managed to find in the documentation that might do what I want is the clone method.
However, if I write
Stack<Integer> stack = (Stack<Integer>) oldstack.clone();
The compiler gives me a warning about unchecked types.
Is there a "proper" way for me to copy a Stack? If not what would be the most sensible thing to do here? I would prefer not to have any warnings, and I feel a little silly iterating and copying over values (although the later might turn out to be the most sensible thing to do).
You can use addAll, I guess:
Stack<Integer> stack = new Stack();
stack.addAll(oldStack);
However, the documentation notes you should use a Deque in preference to the Stack class and there you have what you want immediately:
Deque<Integer> stack = new ArrayDeque<Integer>(oldStack);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With