All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S2293.html Maven / Gradle / Ivy

There is a newer version: 8.6.0.37351
Show newest version

Why is this an issue?

Java uses angular brackets (< and >) to provide a specific type (the "type argument") to a generic type. For instance, List is a generic type, so a list containing strings can be declared with List<String>.

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 sonar.java.source is lower than 7.

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 infer that ArrayList<String>() is the actually desired call.

Code examples

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

Compliant solution

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

References





© 2015 - 2024 Weber Informatics LLC | Privacy Policy