英文:
How it is possible to add element of List in List of Integer in Java
问题
我对 ArrayList 的这种行为感到困惑。
有人可以解释一下吗?
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);
我怎么能在 Integer 的 ArrayList 中添加 String 呢?
有人可以分享一些资源来帮助理解这些内容吗?
英文:
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
得分: 1
原因在这里讨论:https://stackoverflow.com/questions/19253174/are-generics-removed-by-the-compiler-at-compile-time
编译器会对泛型进行检查,但在运行时不会进行检查。
正如 @user 所提到的,您的编译器/IDE 很可能会显示警告,例如:
> List 是原始类型。对泛型类型 List<E> 的引用应该添加参数。
英文:
The reason is discussed here: https://stackoverflow.com/questions/19253174/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<E> should be parameterized
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论