Search code examples
javasonarqubegeneric-programming

Using object name with in the <> , as new ArrayList<String> is correct or it is ok to used only <>?


I created generics like below (1) way , but when Sonar gives me error to replace ,it has (2) . I need to know , what is the best and correct way create generics using <> operator .

  • 1

Noncompliant Code Example

List<String> strings = new ArrayList<String>();  // Noncompliant
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();  // Noncompliant
  • 2

Compliant Solution

List<String> strings = new ArrayList<>();
Map<String,List<Integer>> map = new HashMap<>();

Sonar Code Analysis given below warning :

ava 7 introduced the diamond operator (<>) to reduce the verbosity of generics code. For instance, instead of having to declare a List's type in both its declaration and its constructor, you can now simplify the constructor declaration with <>, and the compiler will infer the type.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.


Solution

  • You are right, using the diamond operator (introduced in Java 7) as:

    List<String> strings = new ArrayList<>();
    Map<String,List<Integer>> map = new HashMap<>();
    

    is better due to letting the compiler to infer the arguments as per the declared type.

    See also: Java 7: Do we really need <> in the diamond operator?