0

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

glennsl
  • 25,730
  • 12
  • 57
  • 71
Sue
  • 1,942
  • 2
  • 9
  • 11

3 Answers3

9

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.

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
  • Just keep in mind that the compiler isn't infinitely intelligent, so you might encounter rare cases where you have to resort to the old style. – Ralf Kleberhoff Mar 26 '18 at 11:35
  • And of course, feel free to include the type information wherever you think it improves readability, e.g. in some deeply nested expression). – Ralf Kleberhoff Mar 26 '18 at 11:37
0

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.

Sai Kishore
  • 326
  • 1
  • 9
  • 16
0

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

arthur
  • 3,117
  • 4
  • 24
  • 33