Type Inference in Java

As part of Generics , Java language supports type safe programming. It allows a type or method to operate on objects of various types while providing compile-time type safety. The most common use case is while using Java Collection framework. For example if you define a list of string and trying to add integer value to the list, compiler throws error.
List list = new ArrayList();
//Compilation Error : he method add(int, String) in the type List is not applicable for the arguments (int)
list.add(10);

As a developer you may always notice redundancy in defining parameter type information in both the side of declaration. As off Java 1.6, language doesn’t provide any feature to overcome it.

Using Static Factory : One possible way to overcome this problem by using static factory methods. If you frequently use typed list or map in application then you can define generic static factory methods which returns you required typed map or list.

public static   HashMap getMapInstance(){    
    return new HashMap();
}
public static  ArrayList getTypedList(){    
    return new ArrayList();
}
Above code snippet defines two static generic factory methods, which returns of specific parameter type list or map. While using these factory methods, java automatically infer parameter types based on left side type declaration.

//Using Static factory Methods, 
Map> map2 = getMapInstance();
Map map3 = getMapInstance();
List doubleList = getTypedList();

Diamond feature in Java 7: In java 7 you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond ’ <>.

Comments

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester