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?
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
1 Answer. Show activity on this post. Adding @Suppress("UNCHECKED_CAST") (also possible through IDEA's Alt + Enter menu) to any of statement, function, class and file should help.
Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.
You can try this:
HashSet<Point> myNewHash = new HashSet<Point>(myHash);
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With