java 复制stack类,如何用Java复制堆栈?

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!

解决方案

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 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());

}

}

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 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);

}

}

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 and suppress the warning with @SuppressWarnings("unchecked").

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值