Showing posts with label warning. Show all posts
Showing posts with label warning. Show all posts

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.

Back to Top


Java warning - Serializable class without serialVersionUID


Problem: warning: [serial] serializable class XXXX has no definition of serialVersionUID

Solution: Two ways to get around this:
1. Add to compiling options: -Xlint:all,-serial (or)
2. Declare serialVersionUID in the code
Eg: public static final long serialVersionUID = 24362462L;
Back to Top


 

Labels