如何在Java中复制一个堆栈?

如何在Java中复制一个堆栈?

只需使用Stack类的clone()方法(该类实现了Cloneable)。

以下是一个使用JUnit的简单测试用例:

@Test

public void test()

{

Stack intStack = new Stack();

for(int i = 0; i < 100; i++)

{

intStack.push(i);

}

Stack copiedStack = (Stack)intStack.clone();

for(int i = 0; i < 100; i++)

{

Assert.assertEquals(intStack.pop(), copiedStack.pop());

}

}

编辑:

tmsimont:这会给我创建一个“未经检查或不安全的操作”警告。有没有方法可以在不生成此问题的情况下完成此操作?

起初我的回应是无法避免警告,但实际上可以使用(通配符)类型来避免:

@Test

public void test()

{

Stack intStack = new Stack();

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 并使用 @SuppressWarnings("unchecked") 来抑制警告。

相关推荐

天龙八部采药在哪学
365bet下注

天龙八部采药在哪学

📅 07-06 👁️ 6979
是谁还不肯放过乔任梁?
365bet下注

是谁还不肯放过乔任梁?

📅 07-10 👁️ 6378
主板怎么放电
beat365体育亚洲版

主板怎么放电

📅 06-27 👁️ 7932