Diamond operator ArrayList
The first statement is clear. The second generates a compilation warning.
The alphabetic iperator was introduced in java 1.7. Since java 1.5 you had to write
ArrayList<Integer> list = new ArrayList<Integer>();
i.e. declare a generic type on both the left and right side of the assignment. Since typical types can be more complex than simple Integer
, it would be very difficult to copy the same definition twice, so they added this cool function to the compiler: you just have to say "This class is generic, use the generic type from the left side of the assignment "using a marker <>
.
Last comment. Please avoid using concrete classes on 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<>();
source to share
A rather advanced topic for Java is called Generics, and that's the explanation for all <> characters.
In essence, you should always write
ArrayList<Integer> list = new ArrayList<>();
Because this is shorthand for
ArrayList<Integer> list = new ArrayList<Integer>();
And you need both type arguments (bits) so that the compiler will give you a warning otherwise.
Record:
ArrayList<Integer> list = new ArrayList();
Creates an ArrayList that can contain any type, and when you try to convert it to ArrayList<Integer>
, the compiler will issue a warning.
EDIT:
Here's a detailed guide on which generics are for and how they work. I'm not sure if you are at this level to understand them fully, but worth a try.
source to share
First, it is a parameterized shared object ArrayList
that is referenced by a parameterized shared reference.
The second is an unparameterized non-shared object ArrayList
that is referenced by a parameterized shared reference.
No, although diamond operators are not needed when you create ArrayList
, it is highly recommended to avoid ClassCastException
or some others RuntimeException
later.
source to share