3

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?

4
  • 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. Commented Sep 30, 2020 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. Commented Sep 30, 2020 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? Commented Sep 30, 2020 at 17:57
  • 7
    @SauravDudeja Here, the details: What is a raw type and why shouldn't we use it? Commented Sep 30, 2020 at 18:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why does the compiler warn integerList.addAll(list);, not an error?
Because the first ArrayList is declared with a raw type. See stackoverflow.com/a/2770692/12323248. If the first line would be typed instead like List<Integer> list = new ArrayList<>(); or List<String> list = new ArrayList<>(); then the compiler would safely indicate an error as soon you try to add another type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.