Monday, February 26, 2007

Java warning while using clone()


Problem: Using clone() raises warnings
Eg:
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("a");
v2 = v1.clone();

Will give the error:
... : incompatible types
found : java.lang.Object
required: java.util.Vector
v2 = v1.clone();
^

Now, casting to generics:
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("a");
v2 = (Vector)v1.clone();

But this raises the warning message:
Util.java:252: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Vector
v2 = (Vector)v1.clone();
^
1 warning

This because clone() returns an Object. But how to use clone() without warnings?

Solution: You can't convert an unqualified type (e.g. Object, Vector) to a
qualified type (e.g. Vector) without warnings.

That's because of type erasure: there is no runtime check that the object is
actually a Vector as (opposed to a simple Vector or Vector) so
the cast is always unsafe and will always result in a warning.

An option would be to NOT use clone() and use your customized function instead. Also, using clone() isn't always recommended by java programmers.

1 comment:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Back to Top


 

Labels