克隆 HashSet 时如何避免未经检查的强制转换警告?
我正在尝试制作名为 myHash 的点哈希集的浅表副本。截至目前,我有以下内容:
HashSet<Point> myNewHash = (HashSet<Point>) myHash.clone();
但是,此代码给了我一个未经检查的强制转换警告。有更好的方法吗?
I'm trying to make a shallow copy of a HashSet of Points called myHash. As of now, I have the following:
HashSet<Point> myNewHash = (HashSet<Point>) myHash.clone();
This code gives me an unchecked cast warning however. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以试试这个:
You can try this:
另一个答案建议使用
new HashSet(myHash)
。然而,clone()
的目的是获取相同类型的新对象。如果myHash
是HashSet
子类的实例,则使用new HashSet(myHash)
。未经检查的强制转换警告只是警告。在很多情况下,强制转换是安全的,但编译器不够智能,无法确定它是安全的。不过,您可以将警告隔离到单个方法中,并使用 @SuppressWarnings("unchecked") 进行注释:
A different answer suggests using
new HashSet<Point>(myHash)
. However, the intent ofclone()
is to obtain a new object of the same type. IfmyHash
is an instance of a subclass ofHashSet
, any additional behavior added by subclassing will be lost by usingnew HashSet<Point>(myHash)
.An unchecked cast warning is just a warning. There are many situations in which the cast is safe, but the compiler just isn't smart enough to determine that it is safe. You can, however, isolate the warning into a single method that can be annotated with
@SuppressWarnings("unchecked")
: