如何在Java中将整数列表的元素添加到整数列表中

huangapple go评论63阅读模式
英文:

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(&quot;test&quot;);

List&lt;Integer&gt; integerList = new ArrayList&lt;&gt;();
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

huangapple
  • 本文由 发表于 2020年10月1日 01:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64142977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定