只需使用Stack类的clone()方法(它实现Cloneable)。
这是一个使用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()); }}编辑:
tmsimont:这会为我创建“未经检查或不安全的操作”警告。有什么办法做到这一点而不会产生此问题?
我最初回答说警告是不可避免的,但实际上使用
<?>(通配符)-typing 是可以避免的:
@Testpublic 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); }}基本上,我想说的是您仍在从
?(未知类型)到进行未经检查的强制转换
Integer,但是没有警告。就个人而言,我还是更喜欢直接投射
Stack<Integer>并使用禁止显示警告
@SuppressWarnings("unchecked")。


