将字符串添加到列表< Integer> [英] Adding String to List<Integer>
本文介绍了将字符串添加到列表< Integer>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码的结果:
public class ListIntegerDemo1 {
public static void addToList (List list){list.add(0067); list.add(bb);}
public static void main(String [] args){
List< Integer> list = new ArrayList<>();
addToList(list);
System.out.println(list.get(0));
$ p $ 0067
$> / code>。
我会期待RuntimeException或类似的情况,因为我将字符串添加到整数列表中。
为什么它没有任何问题?
解决方案在运行时,泛型类型参数是擦除,因此 List< Integer>
变为 List
,您可以添加任何引用类型。
如果您将 addToList(List list)
更改为 addToList(List ,编译器会阻止你在这个方法中将字符串添加到列表中。
The result of the following code:
public class ListIntegerDemo1 {
public static void addToList(List list) {list.add("0067");list.add("bb");}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
addToList(list);
System.out.println(list.get(0));
}
}
is "0067"
.
I would have expected a RuntimeException or similar, as I'm adding a String to an Integer List.
Why is it working without any problem?
解决方案 At run time, the generic type parameters are erased, so List<Integer>
becomes List
, and you can add any reference type to it.
If you change addToList(List list)
to addToList(List<Integer> list)
, the compiler will prevent you from adding Strings to that list in this method.
这篇关于将字符串添加到列表< Integer>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文