Type Inference for Generic Instance Creation

Java 7 : Type Inference for Generic Instance Creation Previously when using generics you had to specify the type twice, in the declaration and the constructor;
List< String> strings = new ArrayList< String>();
In Java 7, you just use the diamond operator without the type;
List< String> strings = new ArrayList<>();  
If the compiler can infer the type arguments from the context, it does all the work for you. Note that you have always been able do a “new ArrayList()” without the type, but this results in an unchecked conversion warning. Type inference becomes even more useful for more complex cases; Before Java 7
Map< String, Map< String,int>> mS = new HashMap< String, Map< String,int>>();
Java 7
Map< String, Map mS = new HashMap();
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List< String> list = new ArrayList<>();
// The following statement should fail since addAll expects  Collection < ? extends String>*/
 list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations. In comparison, the following example compiles: // The following statements compile:
List< ? extends String> list2 = new ArrayList<>();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...