Thursday, October 18, 2007

Generics (A Compile-Time Protection)

All the generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode. None of your typing information exists at runtime.
In other words, even though you write
List myList = new ArrayList();


By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:
List myList = new ArrayList();

The compiler even inserts the casts for you—the casts you had to do to get things out of a pre-Java 5 collection. Think of generics as strictly a compile-time protection. The compiler uses generic type information (the in the angle brackets) to make sure that your code doesn't put the wrong things into a collection, and that you do not assign what you get from a collection to the wrong reference type. But NONE of this protection exists at runtime.

public class GenericTest
{
public static void main(String[] args)
{
List list1 = new ArrayList();
list1.add(7);
list1.add(16);
NonGeneric ng = new NonGeneric ();
ng.insert(list1);
System.out.println(list1);
}
}

class NonGeneric
{
void insert(List list)
{
list.add("hello");
}
}

Above code will compile and run without errors. Output will be
[7, 16, hello]

No comments: