java中cast的用法,java:如何使用clone()以及如何使用cast检查

This code:

class RawStringIterator {

java.util.Stack stateStack = new java.util.Stack();

RawStringIterator(RawStringIterator i) {

stateStack = (java.util.Stack) i.stateStack.clone();

}

/* ... */

}

gives me this warning:

Type safety: Unchecked cast from Object to Stack

I guess I can ignore the warning here. But I wonder about how to use clone() in general? Do I always have to use a @SuppressWarnings("unchecked") every time I use clone()? Or should I always do the completely redundant extra check?

解决方案

If you have the choice, the best is not to implement / use clone() at all, because it is a broken API. Just implement / use a copy constructor instead.

If for some pressing reason you must use clone() but can change its implementation, consider declaring Stack.clone() to return Stack instead of Object - covariant return types are legal since Java5.

Update: if the Stack in question is java.util.Stack, consider its Javadoc:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值