How to avoid unchecked cast warning when cloning a

2020-05-25 07:51发布

问题:

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