How it is possible to add element of List in List of Integer in Java

Viewed 130

I am confused with this behavior of Array List. Can someone please explain this

List list = new ArrayList();
list.add(1);
list.add("test");

List<Integer> integerList = new ArrayList<>();
integerList.add(123);
integerList.add(456);
integerList.addAll(list);

System.out.println(integerList);

How can I add String in Integer arrayList Can someone please share some resource to understand these things?

1 Answers

The reason is discussed here: Are generics removed by the compiler at compile time

Generics are checked by the compiler, but not afterwards during runtime.

As @user mentioned, your compiler/IDE will most likely show a warning e.g.

List is a raw type. References to generic type List should be parameterized

Related