esa*_*saj 26
只需使用Stack-class的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());
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
tmsimont:这会为我创建一个"未经检查或不安全的操作"警告.没有产生这个问题的任何方法吗?
我起初回应说警告是不可避免的,但实际上可以避免使用<?>(通配符)-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);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我会说你还在从?(未知类型)进行未经检查的演员表Integer,但是没有警告.就个人而言,我仍然倾向于直接投入Stack<Integer>并压制警告@SuppressWarnings("unchecked").
msa*_*ord 20
Stack扩展Vector,所以你可以新建一个新的Stack并用于.addAll(...)复制项目:
Stack<Type> newStack = new Stack<Type>();
newStack.addAll(oldStack);
Run Code Online (Sandbox Code Playgroud)