Consider the following serialization/deserialization test class:
import java.io.*;
import java.util.*;
public class TestSerialzationAndGenerics {
public static void main(String[] args) throws Exception {
List listUntyped = new ArrayList();
Set<Object> setTyped = new HashSet<Object>();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( listUntyped );
oos.writeObject( setTyped );
ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) );
List listUntypedDeser = (List) ois.readObject();
Set<Object> setTypedDeser = (Set<Object>) ois.readObject();
System.out.println("listUntyped.equals(listUntypedDeser): " + listUntyped.equals(listUntypedDeser));
System.out.println("setTyped.equals(setTypedDeser): " + setTyped.equals(setTypedDeser));
}
}
Critical: compile it with
-Xlint:all
Then run it. It should work just fine, outputting:
listUntyped.equals(listUntypedDeser): true
setTyped.equals(setTypedDeser): true
as expected.
My question actually concerns the compilation step: why does the line
List listUntypedDeser = (List) ois.readObject();
compile just fine, but the line
Set<Object> setTypedDeser = (Set<Object>) ois.readObject();
cause javac to emit this warning:
TestSerialzationAndGenerics.java:17: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Set<java.lang.Object>
? Both lines are just casts after all, but one is an untyped Collection cast while the other one is a cast to a generified Collection. For some reason, javac seems to have a problem with generified casts.
Am I doing something wrong?
Is there any way around this?
A google search only turned up 3 relevant postings, with only 1 in english:
http://forum.java.sun.com/thread.jspa?messageID=3655969
This forum posting touches on this issue, but they never addressed my question above which is why the generified cast is a problem when the untyped cast is not.
Eargerly awaiting your thoughts...