Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a stack in Java?

Tags:

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!

like image 595
Pankaj Udhas Avatar asked Oct 27 '11 17:10

Pankaj Udhas


2 Answers

Just use the clone() -method of the Stack-class (it implements Cloneable).

Here's a simple test-case with JUnit:

@Test    public void test() {     Stack<Integer> intStack = new Stack<Integer>();     for(int i = 0; i < 100; i++)             {         intStack.push(i);     }      Stack<Integer> copiedStack = (Stack<Integer>)intStack.clone();      for(int i = 0; i < 100; i++)                 {         Assert.assertEquals(intStack.pop(), copiedStack.pop());     } } 

Edit:

tmsimont: This creates a "unchecked or unsafe operations" warning for me. Any way to do this without generating this problem?

I at first responded that the warning would be unavoidable, but actually it is avoidable using <?> (wildcard) -typing:

@Test public void test() {     Stack<Integer> intStack = new Stack<Integer>();     for(int i = 0; i < 100; i++)     {         intStack.push(i);     }      //No warning     Stack<?> copiedStack = (Stack<?>)intStack.clone();      for(int i = 0; i < 100; i++)     {         Integer value = (Integer)copiedStack.pop(); //Won't cause a warning, no matter to which type you cast (String, Float...), but will throw ClassCastException at runtime if the type is wrong         Assert.assertEquals(intStack.pop(), value);     } } 

Basically I'd say you're still doing an unchecked cast from ? (unknown type) to Integer, but there's no warning. Personally, I'd still prefer to cast directly into Stack<Integer> and suppress the warning with @SuppressWarnings("unchecked").

like image 195
esaj Avatar answered Oct 31 '22 17:10

esaj


Stack extends Vector, so you can just new up a new Stack and use .addAll(...) to copy the items:

Stack<Type> newStack = new Stack<Type>(); newStack.addAll(oldStack); 
like image 33
clstrfsck Avatar answered Oct 31 '22 18:10

clstrfsck