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 ?
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.
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.
It's called diamond operator and infers the generic type from the left hand side, if possible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With