Sonar complaining "The diamond operator ("<>") should be used"

Viewed 4542

So I have below line of code in my file

List<String> nameList = new ArrayList<String>();

Now each time I run sonar scans it shows an error in above line saying I should use diamond operator instead. Now I understand that from Java7 compiler will automatically detect and supply the type of objects for ArrayList but my question is there a harm if I do it myself while declaring the class ?

Here is the rule link from Sonar website. I really don't understand the example they are supplying with this rule.

Is there any performance, efficiency or any other type of gain in changing the code to what Sonar is suggesting ?

3 Answers

Less you have helpless and duplicate code and more the code is readable and maintainable.

List<String> nameList = new ArrayList<String>();

or

List<String> nameList = new ArrayList<>();

Ok, not a lot of differences.

But suppose now that you have to change the generic: String by Integer, with the first way you have to do two modifications:

List<Integer> nameList = new ArrayList<Integer>();
      ^------               -------------^

Really not nice.

With the diamond a single one is required :

List<Integer> nameList = new ArrayList<>();
      ^---             

But take another example :

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

or

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

It makes things clearer.

In an application, you generally declare and instantiate tons of collections and generic classes. Refactoring it is really cheap. So just do it.

is there a harm if I do it myself while declaring the class ?

No, there is not any harm in doing it this way, except for the extra verbosity added to the code. From the same rule link we can read that

Java 7 introduced the diamond operator (<>) to reduce the verbosity of generics code


Is there any performance, efficiency or any other type of gain in changing the code to what Sonar is suggesting ?

Except for the fact that you (and your team) will have a less verbose code, no, there is not.


Further readings:

The whole point behind this rule is: In java 7 the compiler got the ability to infer the type for the constructor from the type itself.

Why should you omit the generic type in the constructor?

2 things:

  • it is more verbose to specify the type twice
  • you do not need to change the type for the generic twice if you decide to change the collection.

Is it harmful to leave it as it is? Not really. But it's always better to have a consistent code style in your team. So if you team uses sonar for codestyle checking you should conform to it for the sake of consistency.

Related