Suggested Pages

Tuesday, January 31, 2017

Java Generics

Motivations


Generics have been introduced in the Java language to avoid runtime errors and allow the compiler to detect problems. Suppose you have the following code:
    
    String count="count:";
    Integer countNumber=20;
    List list=new LinkedList();
    list.add(count);
    list.add(countNumber);
    Iterator it=list.iterator();
    String result="";
    while(it.hasNext()){
     result+=(String)it.next();
    }
    System.out.println(result);
The code above compiles successfully but launches this error at runtime:
 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

if we replace the code above with the code shown below
   
   String count="count:";
   Integer countNumber=20;
   List<string> list=new LinkedList<string>();
   list.add(count);
   list.add(countNumber);
   Iterator<string> it=list.iterator();
   String result="";
   while(it.hasNext()){
     result+=it.next();
   }
   System.out.println(result);
Now the code doesn't compile successfully but launches the following compiler error:
The method add(String) in the type List is not applicable for the arguments (Integer)
As you can see problems are detected at compile time and not at runtime

Erasure


Generics work at runtime with erasure, so the compiler removes all of the information on type parameters of generics method or class. This compiler behaviour allows Java Applications to be compatible with previous Java versions that don't make use of generics. So we can consider Generics Types as information given to the compiler, but at runtime no information is present on Generics Types.
We can distinguish two terms :
  • Generics Types: List<String>
  • Raw Types (legacy code): List

Besides generics can be used at different level:
  • Generic Class: a class that makes use of variable types;
  • Generic Method: a method that makes use of variable types.

1 comment :

Suggested Pages