Java Reference
In-Depth Information
be an operator in Java) was introduced. The diamond allows the compiler to infer the
type argument(s) from the context of the parameterized type usage. A simple example
of the diamond usage follows:
List<Integer> eList = new ArrayList<>();
Notice there is no type argument specified between the angle brackets when instan-
tiating the ArrayList . The compiler can easily infer the type to be Integer , based
on the context of the assignment or initializer. Integer is the only type that would
work in this context. In fact, the Java compiler (and most compliant IDEs) will actually
warn you if you do not use a diamond where it is possible to use it. Another more com-
plex example shows the benefit even better:
Map<Integer, List<String>> aMap = new HashMap<>(); //
Nice!
The diamond can similarly be used in return statements, as well as in method ar-
guments:
// diamond in method return
public static List<String> getEmptyList() {
return new ArrayList<>();
}
// diamond in method argument
List<List<String>> gList = new ArrayList<>();
gList.set(0, new ArrayList<>(Arrays.asList("a", "b")));
Note that using the diamond as shown here is not the same as using a raw type. The
following is not equivalent to the declaration of aMap that uses the diamond; it will
result in an “unchecked conversion” warning, and possibly a raw type warning, from
the compiler:
Map<Integer, List<String>> bMap = new HashMap();
//
compiler warnings; avoid raw types
The discussion around why this is different than the diamond example is beyond
the scope of this recipe. If you remember to avoid the use of raw types, you shouldn't
Search WWH ::




Custom Search