2

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?

  • 8
    It works because Java doesn't check the list at runtime, and `list` was declared with a raw type, which basically lets you bypass compile time checks for generics-related stuff. You should have gotten a warning, though. – user Sep 30 '20 at 17:42
  • Thanks for the comment @user. But I didn't see any warning there. I am very confused with this. Can you please explain this is more details. – Saurav Dudeja Sep 30 '20 at 17:46
  • 2
    I get a warning on this line of your code: `integerList.addAll(list);` Are you saying that you don't get a warning for that line? – Abra Sep 30 '20 at 17:57
  • 7
    @SauravDudeja Here, the details: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/a/2770692/12323248) – akuzminykh Sep 30 '20 at 18:04

1 Answers1

1

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

martinspielmann
  • 536
  • 6
  • 19
  • Why does the compiler warn `integerList.addAll(list);`, not an error? –  Sep 30 '20 at 20:50
  • Because the first `ArrayList` is declared with a raw type. See https://stackoverflow.com/a/2770692/12323248. If the first line would be typed instead like `List list = new ArrayList<>();` or `List list = new ArrayList<>();` then the compiler would safely indicate an error as soon you try to add another type. – martinspielmann Sep 30 '20 at 20:54