Wednesday, September 16, 2009

Generics with non - generics

When we use generics we use the syntax as List< Integer > newList= new ArrayList< Integer >(), Can there be a way by which I can put a string into it. How can I cheat....????
Of course there is a way. This is by mixing generic code with non-generic code.
This is how it can be done.
public class TestGeneric{
   public static void main(String args[])
  {
       List newList = new ArrayList();
       newList.add(7); // autoboxing feature
       newList.add(new Integer(10)); // normal adding objects
       insert(newList);
  }
  public void insert(List nonGenericList)
 {
     nonGenericList.add("42"); // valid compiles fine and surprisingly runs fine too.....check the reason y below
 }
}
The reason why this compiles and runs fine is because of a mechanism called type erasure which the compiler uses. The generic that we use to represent a list of integers is only used by the compiler it is not used during runtime. If you see in the code above the insert method takes in a non generic list while the list being passed to the method is a list which consists of integers. Now in the insert method since the list is not generic it is possible to add a string value.. What happens during runtime is that the generic code gets converted into the non generic code i.e the byte code that is generated from a non generic code and a generic code is same.This mechanism is called type erasure. The generic code only provides compile time protection but not runtime protection.