Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid unchecked cast warning when cloning a HashSet?

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?

like image 771
Tim Avatar asked Feb 12 '12 21:02

Tim


People also ask

How can I avoid unchecked cast warnings?

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.

How do you stop unchecked cast Kotlin?

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.

What is unchecked cast in Java?

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.


2 Answers

You can try this:

HashSet<Point> myNewHash = new HashSet<Point>(myHash); 
like image 79
Ted Hopp Avatar answered Oct 08 '22 14:10

Ted Hopp


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()); } 
like image 26
Atsby Avatar answered Oct 08 '22 13:10

Atsby