Java:如何使用clone()和演员检查呢
此代码:
class RawStringIterator {
java.util.Stack<State> stateStack = new java.util.Stack<State>();
RawStringIterator(RawStringIterator i) {
stateStack = (java.util.Stack<State>) i.stateStack.clone();
}
/* ... */
}
给我这个警告:
Type safety: Unchecked cast from Object to Stack<Utils.OperatorTree.RawStringIterator.State>
我想我可以在这里忽略警告。但是我想知道如何使用 clone()
通常?我是否总是必须使用 @suppresswarnings(“ UNCANCED”)
每次使用 clone()
?还是我应该始终进行完全多余的额外检查?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您有选择的话,最好的是完全不是实现/使用
clone()
,因为这是一个损坏的API 。只需实现 /使用复制构造函数即可。如果出于某种紧迫的原因,您必须使用
clone()
但可以更改其实现,请考虑声明stack&lt; t&gt; .clone()
才能返回stack&lt; t&gt;
而不是对象
- 协变返回类型是合法的,因为Java5。更新:如果
stack
是java.util.stack
,请考虑它的javadoc :和例如 a>提供复制构造函数。
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 declaringStack<T>.clone()
to returnStack<T>
instead ofObject
- covariant return types are legal since Java5.Update: if the
Stack
in question isjava.util.Stack
, consider its Javadoc:And e.g.
ArrayDeque
provides a copy constructor.没有办法避免这里的演员阵容。
clone()
返回object
,如果是java.util.stack
,它不使用共同变化的返回类型。如果这不是
java.util.stack
,则请勿实现clone()
- 很难正确正确。改为复制构造符。There is no way to avoid the cast here.
clone()
returnsObject
, if it isjava.util.Stack
, it is not making use of co-variant return types.If this is not
java.util.Stack
, then don't implementclone()
- it's really hard to get it right. Make a copy-constructor instead.您别无选择,只能忽略它。
虽然不直接相关(因为您没有编写
clone()
方法),但此条目在 Java Generics常见问题可以很好地阅读(整个FAQ也是如此!)You have very little choice but to ignore it.
Whilst not directly relevant (because you're not writing a
clone()
method), this entry in the Java Generics FAQ makes good reading (as does the whole FAQ!)是的,每次使用
clone()
时,您需要明确抑制警告。这是您可能希望使用复制构造函数而不是
clone()
(如果有)的原因之一。顺便说一句,当使用
RAWSTRINGITERATOR(RAWSTRINGITERATOR I)
构造函数时,不必要的第一个初始化 stateStack 是不必要的:您可能需要删除它。
Yes, you'll need to explicitly suppress the warnings each time you use
clone()
.This is one of the reasons you might prefer to use copy constructors instead of
clone()
, if available.By the way in your code, when the
RawStringIterator(RawStringIterator i)
constructor is used, the first initialisation ofstateStack
is unnecessary:You might want to remove that.