Saturday, August 13, 2011

Change in use of generic in new version of JDK

With new JDK, there is change in use of generics and this new improved type inference for generic instance creation makes code more cleaner. It also removes unnecessarily duplication of type parameter while using generics.
With this change, we need not to mention type parameter while creating type of object on both side of expression like :

List<String> objectList = new ArrayList<>(); // change which is in new JDK 7

Earlier, we use to mention type parameter on both side of expression like :

List<String> objectList = new ArrayList<String>(); // prior to JDK 7

Program example :

import java.util.ArrayList;
public class GenericTypeInference {
public static void main(String[] args) {
ArrayList<String> nameList = new ArrayList<>(); // with new JDK, need not to mention type parameter on both side of expression
nameList.add("Rev");
nameList.add("John");
nameList.add("Sean");
System.out.println("Name list size : " + nameList.size());
System.out.println("Name list in string : " + nameList.toString());
for (String name : nameList) {
System.out.println("Name from list : " + name);
}
}

}

This feature make code more cleaner and prevents unnecessary type parameter duplication.

4 comments:

  1. Hi Abhishek ,
    Great Info , kindly mention the usage of generics under Comparater and Comparable interface scenarios.If possible please include usage in generic methods.

    ReplyDelete
  2. @Harsh : I will make new post for usage of generics in comparable and comparator and following is the url : http://javareharsed.blogspot.com/2011/08/usage-of-generics-in-comparable-and.html

    For methods, I will create new post soon. Provide your feedbacks about new post.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. @Eran Thanks for your comments. I worked on Java so idea about that but I think .net also have great features.

    ReplyDelete