3

What is the difference between

ArrayList<Integer> list = new ArrayList<>();

and

ArrayList<Integer> list = new ArrayList();

Are the diamond operator when I create a new ArrayList necessary?

0

3 Answers 3

6

The first statement is clear. The second generates compilation warning.

Diamond iperator was introduced to java 1.7. Starting from java 1.5 you had to write

ArrayList<Integer> list = new ArrayList<Integer>();

i.e. declare the generic type both on the left and right sides of the assignment. Since generic types may be more complex than just Integer it was annoying to copy exactly the same definition twice, so they added this cool feature to compiler: you just have to say: "this class is generic, use the generic type from the left side of the assignment" by using <> marker.

BTW the last comment. Please avoid using concrete classes in the left side of assignments and method definitions. The following is much better:

List<Integer> list = new ArrayList<>();

or even

Collection<Integer> list = new ArrayList<>();

or often even

Iterable<Integer> list = new ArrayList<>();
1
  • very informative answer but could you please explain or provide links where to read about this statement: Please avoid using concrete classes in the left side of assignments and method definitions. The following is much better:... please why, thank you Feb 2, 2019 at 20:45
1

A rather advanced topic for Java is called Generics and that is the explanation for all the <> symbols.

In essence, you should always write

ArrayList<Integer> list = new ArrayList<>();

Because it is shorthand for

ArrayList<Integer> list = new ArrayList<Integer>();

And you need both type arguments (the bit) to match otherwise the compiler will give you a warning.

Writing:

ArrayList<Integer> list = new ArrayList();

Creates an ArrayList that can hold any type, and when you try to convert it into an ArrayList<Integer> the compiler will throw a warning.

EDIT:

Here is a in-depth guide on what generics are for and how they work. I'm not sure if you're at the level to understand them fully yet, but it's worth a try.

https://docs.oracle.com/javase/tutorial/java/generics/

0

First is the parameterized generic object of ArrayList, referenced by a parameterized generic reference.

Second is non-parameterized non-generic object of ArrayList, referenced by a parameterized generic reference.

No, although the diamond operators are not necessary when you create an ArrayList, it is highly recommended to avoid ClassCastException or some other RuntimeException later on.

Not the answer you're looking for? Browse other questions tagged or ask your own question.