How to avoid unchecked cast warning when cloning a HashSet?

拈花ヽ惹草 提交于 2019-12-03 10:57:36

问题


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?


回答1:


You can try this:

HashSet<Point> myNewHash = new HashSet<Point>(myHash);



回答2:


A different answer suggests using new HashSet<Point>(myHash). However, the intent of clone() is to obtain a new object of the same type. If myHash is an instance of a subclass of HashSet, any additional behavior added by subclassing will be lost by using new 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"):

@SuppressWarnings("unchecked")
static <T implements Cloneable> clone(T o) { return (T)(o.clone()); }


来源:https://stackoverflow.com/questions/9252803/how-to-avoid-unchecked-cast-warning-when-cloning-a-hashset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!