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.
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();
<>
) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond ’ <>’.
Comments
Post a Comment