Java and generics: handle with care

Eric | November 7, 2007

Type this in Eclipse and hit “save”. It will happily give you a compile time error in the third line. After all, you are casting a set of Strings to a String, which clearly is not well-typed.

Set<String> stringSet = new HashSet<String>();
Set<String> otherStringSet = new HashSet<String>();
otherStringSet.add((String) stringSet);

Now, type this here in Eclipse… it’s the same code, just with the interface type <List> where there was the class type <String> before.

Set<List> listSet = new HashSet<List>();
Set<List> otherListSet = new HashSet<List>();
otherListSet.add((List) listSet);

What happens? The code happily compiles!!! Does it run? Well, yes until line 3, where you get a ClassCastException. And the worst: The same happens when you use javac!!! So what? Is that a flaw in the language after all? Or are just all compiler people having a hard time getting their typechecks right? What are generics good for? Since when is a Set a List? I hope that bug 209071 can bring some insight.