Type Inference for Generic Instance Creation in Java SE - TopicsExpress



          

Type Inference for Generic Instance Creation in Java SE 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. For example, consider the following variable declaration: Map myMap = new HashMap(); In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (): Map myMap = new HashMap(); Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map type: Map myMap = new HashMap(); // unchecked conversion warning 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 list = new ArrayList(); list.add("A"); // The following statement should fail since addAll expects // Collection
Posted on: Sat, 24 Aug 2013 04:30:00 +0000

Trending Topics



Recently Viewed Topics




© 2015