Java Generic Class

http://download.oracle.com/javase/tutorial/extra/generics/fineprint.html

A Generic Class is Shared by All Its Invocations

What does the following code fragment print?

List <String> l1 = new ArrayList<String>(); 

List<Integer> l2 = new ArrayList<Integer>(); 

System.out.println(l1.getClass() == l2.getClass()); 

You might be tempted to say false, but you’d be wrong. It prints true, because all instances of a generic class have the same run-time class, regardless of their actual type parameters.

Indeed, what makes a class generic is the fact that it has the same behavior for all of its possible type parameters; the same class can be viewed as having many different types.

As consequence, the static variables and methods of a class are also shared among all the instances. That is why it is illegal to refer to the type parameters of a type declaration in a static method or initializer, or in the declaration or initializer of a static variable.

Casts and InstanceOf

Another implication of the fact that a generic class is shared among all its instances, is that it usually makes no sense to ask an instance if it is an instance of a particular invocation of a generic type:

Collection cs = new ArrayList<String>(); 

if (cs instanceof Collection<String>) { …} // Illegal.

similarly, a cast such as

Collection<String> cstr = (Collection<String>) cs; // Unchecked warning,

gives an unchecked warning, since this isn’t something the runtime system is going to check for you.

The same is true of type variables

<T> T badCast(T t, Object o) {return (T) o; // Unchecked warning. 

 } 

Type variables don’t exist at run time. This means that they entail no performance overhead in either time nor space, which is nice. Unfortunately, it also means that you can’t reliably use them in casts.