Type checking for Java Generics – Basics
June 11th, 2009
2 comments
With introduction of Generics in Java, type checking in Java opened up a can of complex variations and concepts. During the compile type, the compiler enforces stricter type checking for a generics implements. That is
List<String> listOfStrings = new ArrayList<String>(1);
listOfStrings.add(new Integer(1)); //will throw a compilation error
However during the runtime, the JVM doesnt maintain type information about generics, and this is ‘type erasure’. So effectively a code snippet such as this
List<String> listOfStrings = new ArrayList<String>(1); listOfStrings.add("HelloWorld"); String addedElement = listOfStrings.get(0);
would get converted to in
List listOfStrings = new ArrayList(1); listOfStrings.add("HelloWorld"); String addedElement = (String)listOfStrings.get(0);
Behind the scenes, there are 2 passes of compilation, in which the first pass handles the type checking, and in the second pass, the type information is erased and written to the class file.
Categories: Uncategorized