gpt4 book ai didi

java - Java 编译器忽略了完全限定的泛型类型转换错误?

转载 作者:行者123 更新时间:2023-12-01 12:20:09 25 4
gpt4 key购买 nike

泛型有意在编译时进行更强的类型检查。然而,在学习官方Java教程时,我遇到了这个:

However, in some cases the compiler knows that a type parameter is always valid and allows the cast. For example:

List<String> l1 = ...;
ArrayList<String> l2 = (ArrayList<String>)l1; // OK

来自http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCast .

我已经尝试并测试了这一点(完全反射(reflect)了文档):

List<String> l1 = new LinkedList<String>();
ArrayList<String> l2 = (ArrayList<String>)l1; // OK

虽然一切都非常明确(没有分配给 Object 变量,没有通配符等),但编译器无法预测随后出现的运行时错误:

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.util.ArrayList

100% 困惑。

最佳答案

重读该链接 - 它并不是说您可以将 LinkedList 转换为 ArrayList。它指出您可以将 StringList 向下转换为(大概是程序员已知的)ArrayList 类型字符串。他们试图说明的是通用类型参数之间的差异。他们的第一个示例展示了从 Integer 集合到 Number 集合的转换,这是不允许的。

Typically, you cannot cast to a parameterized type unless it is parameterized by unbounded wildcards. For example:

List li = new ArrayList<>(); List ln = (List) li; // compile-time error

However, in some cases the compiler knows that a type parameter is always valid and allows the cast. For example:

List l1 = ...; ArrayList l2 = (ArrayList)l1; // OK

关于java - Java 编译器忽略了完全限定的泛型类型转换错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724944/

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