When you say ArrayList<>(),
the type in angle brackets is inferred from the declaration, so it resolves to ArrayList<Integer>
at compile time.
If you omit angle brackets, then the assignment uses raw type, i.e. collection type without any information of the element type. No type inference is done by the compiler for this assignment.
Both lines will not compile:
list1.add("hello")
list2.add("hello")
because both list1
and list2
variables are declared as ArrayList<String>
.
The point of specifying <>
is that the assignment of ArrayList()
to ArrayList<String>
should generate a compiler warning of unchecked assignment, because the compiler can't verify that the raw typed collection to the right of the =
sign contains only Integer
s. In a simple case such as yours, you can control the correctness of the code visually. But consider a more complex scenario:
ArrayList rawList = new ArrayList();
rawList.add("one");
ArrayList<Integer> list = rawList;
Here you break the generic system by assigning a raw list that contains a String
to a typed list variable that should contain only Integer
s. That's where the compiler warning of unchecked assignment comes in handy.