Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 570
Amit Avatar asked Aug 31 '18 15:08

Amit


People also ask

What is Diamond notation used for?

The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable.

What is Diamond inference in Java?

The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics: List<String> cars = new ArrayList<>(); The Java 1.7 compiler's type inference feature determines the most suitable constructor declaration that matches the invocation.

Which of the following options is the correct name for empty type parameter rectangle square diamond circle?

It's called diamond operator and infers the generic type from the left hand side, if possible.


1 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.

like image 168
davidxxx Avatar answered Oct 03 '22 00:10

davidxxx