Why is this an issue?
Java uses angular brackets (
>) to provide a specific type (the "type argument") to a generic type. For
List is a generic type, so a list containing strings can be declared with
Prior to Java 7, the type argument had to be provided explicitly for every occurrence where generics were used. This often caused redundancy, as
the type argument would have to be provided both when a field is declared and initialized.
Java 7 introduced the diamond operator (
<>) to reduce the code’s verbosity in some situations. The type argument between the
angular brackets should be omitted if the compiler can infer it.
Since the diamond operator was only introduced in Java 7, this rule is automatically disabled when the project’s
How to fix it
The type argument should be omitted in the initialization if it is already present in the declaration of a field or variable.
For instance, a field with type
List<String> can be initialized with
ArrayList<>(), as the compiler will
ArrayList<String>() is the actually desired call.
Noncompliant code example
List<String> strings = new ArrayList<String>(); // Noncompliant, the compiler can infer the type argument of the constructor invocation
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>(); // Noncompliant, the compiler can also infer complex type arguments
List<String> strings = new ArrayList<>(); // Compliant, the compiler will infer the type argument
Map<String,List<Integer>> map = new HashMap<>(); // Compliant, the compiler will infer the type argument