Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a java.util.Stack in Java [duplicate]

Tags:

java

stack

copy

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

like image 472
math4tots Avatar asked Nov 29 '25 09:11

math4tots


1 Answers

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);
like image 190
Joey Avatar answered Dec 02 '25 00:12

Joey