0

What is the difference between raw types and generic types in this declaration

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

List<Integer> list2 = new ArrayList();

for these declaration i can't do

list1.add("hello");
list2.add("hello");

so where is the difference

on other word what is the benefit of the angle brackets in first declaration

ahmed S
  • 336
  • 3
  • 12

1 Answers1

1

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 Integers. 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 Integers. That's where the compiler warning of unchecked assignment comes in handy.

Forketyfork
  • 7,416
  • 1
  • 26
  • 33