如何将整数添加到String ArrayList中?

Ace*_*oud 13 java arraylist

List list = new ArrayList<String>() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);
Run Code Online (Sandbox Code Playgroud)

上面的代码有一个类型为List的引用,引用了String类型的ArrayList实例.当执行该行时,是不是将1添加到ArrayList(String类型)?如果是,那么为什么允许这样做?list.add(1)

Pet*_*rey 15

您已使用类型擦除,这意味着您已忽略以前设置的通用检查.你可以放弃这个,因为泛型是一个编译时功能,在运行时不会检查.

你有什么相同的

List list = new ArrayList() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);
Run Code Online (Sandbox Code Playgroud)

要么

List<Integer> list = new ArrayList<Integer>() ;
list.add(1) ;
Integer hello = list.get(0); // generics add an implicit cast here
System.out.println(hello);
Run Code Online (Sandbox Code Playgroud)

如果查看编译器生成的字节代码,就无法区分它们.

有趣的是,你可以做到这一点

List<String> strings = new ArrayList<String>();
@SuppressWarnings("unchecked");
List<Integer> ints = (List) strings;
ints.add(1);

System.out.println(strings); // ok
String s= strings.get(0); // throws a ClassCastException
Run Code Online (Sandbox Code Playgroud)


Vla*_*nov 12

问题是您的list变量具有原始类型,您可以将任何类型的对象添加到此列表中.为了解决这个问题只需要声明它作为一个ListString的:

List<String> list = new ArrayList<String>() ;
Run Code Online (Sandbox Code Playgroud)