I have a stack A and I want to create a stack B that is identical to stack A. I don't want stack B to simply be a pointer to A -- I actually want to create a new stack B that contains the same elements as stack A in the same order as stack A. Stack A is a stack of strings.
Thanks!
The Stack class is a sub-class of AbstractList.
Simply treat it like an AbstractList, iterate through the elements in the stack using the
get(int index)
method, from 0 to the length of your list/stack, and add the elements to the new stack.This won't copy the elements - it will add the elements to the new stack. If you need to copy the elements as well, you'll need to go another level deep and create copies of the elements, and add those to the new stack.
You can do full (or "deep") copies, by using the
clone
method, but note that the object must implement the Clonable interface in order to get deep copies of objects.You want to use the clone method.
Stack
extendsVector
, so you can just new up a newStack
and use.addAll(...)
to copy the items:Just use the clone() -method of the Stack-class (it implements Cloneable).
Here's a simple test-case with JUnit:
Edit:
I at first responded that the warning would be unavoidable, but actually it is avoidable using
<?>
(wildcard) -typing:Basically I'd say you're still doing an unchecked cast from
?
(unknown type) toInteger
, but there's no warning. Personally, I'd still prefer to cast directly intoStack<Integer>
and suppress the warning with@SuppressWarnings("unchecked")
.