gpt4 book ai didi

java - 使用通用集合

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:56 26 4
gpt4 key购买 nike

编译并运行成功!

List a=new ArrayList<String>();
a.add(new Integer(5));

有人能解释一下吗?

最佳答案

原因是您将变量 a 声明为原始列表,即没有任何关联类型的 List:

List a = new ArrayList<String>();

就此而言,即使这样也可以编译并运行:

List a = new ArrayList<Date>();
a.add(new Integer(5));

还有关于genericstype erasure 的说明:

泛型由 Java 编译器实现为称为删除的前端转换。类型删除适用于泛型的使用。使用泛型时,它们会转换为编译时检查和运行时类型转换。

由于类型删除机制,此代码:

List<String> a = new ArrayList<String>();
a.add("foo");
String x = a.get(0);

编译成:

List a = new ArrayList();
a.add("foo");
String x = (String) a.get(0);

同样你的代码:

List a = new ArrayList<String>();
a.add(new Integer(5));

被编译成这个(由于类型删除):

List a = new ArrayList();
a.add(new Integer(5));

因此不会产生编译或运行时错误。

但是,当您尝试从列表中获取项目时,您会注意到不同之处:

int i = a.get(0); // compilation error due to type mismatch

这是因为您的列表被声明为原始类型。为避免此错误,您需要使用泛型来声明您的列表,或者像上面那样进行类型转换。即

在列表中使用通用类型:

List<Integer> a = new ArrayList<Integer>();
a.add(new Integer(5));
int i = a.get(0);

否则执行此转换:(不推荐)

List a=new ArrayList<Date>();
a.add(new Integer(5));
int i = (Integer) a.get(0);

PS:请注意,在运行时无法找出特定类型,例如字符串用于声明您的列表对象。

关于java - 使用通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17943403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com