What's the most right and recommended java expression:
new ArrayList<>();
Or
new ArrayList<String>();
My question goes on any Object that contains any type (like Map).
What's the most right and recommended java expression:
new ArrayList<>();
Or
new ArrayList<String>();
My question goes on any Object that contains any type (like Map).
The first way is valid from Java 7 and you need not to have type init which called as Diamond Operator.
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
The purpose of the diamond operator is to simplify instantiation of generic classes. So just to keep the things simple prefer first way.
Since Java 7, the Diamond operator is used to reduce the verbosity.
If you use version >=7, it is recommended to use the first one.
Go through this.
From Java >= 7 none of them is better than other. The compiler will basically handle them both the same way.
Before Java 7 you had to specificy your Generic Type.
List<String> myStrings = new ArrayList<String>();
But since Java 7, you can do:
List<String> myStrings = new ArrayList<>();
And the compiler is gonna find out the rigth target type for your Collection and inject into your Collection. this is called Type Inference for Generic Instance Creation
Again none is better or recommended above the other, it is just to facilitate your job, so that you write less code. If you are a new java programmer trying to understand the language, you should start with the former. If you are a experienced programmer you do the latter