gpt4 book ai didi

Java 泛型 : Wildcard capture misunderstanding

转载 作者:行者123 更新时间:2023-11-29 08:45:57 28 4
gpt4 key购买 nike

阅读 Java 在线教程我对通配符捕获一无所知。例如:

    import java.util.List;
public class WildcardError {
void foo(List<?> i) {
i.set(0, i.get(0));
}
}

为什么编译器不能安全地保留赋值?

它知道,通过执行例如带有Integer List 的方法,它从i.get 获得一个Integer 值。因此它尝试将索引 0 处的 Integer 值设置为相同的整数列表 (i)。

所以,怎么了?为什么要写通配符助手?

最佳答案

why the compiler can't retain the assignment safe? It knows that,by executing for instance, the method with an Integer List, it gets from i.get an Integer value. So it try to set an Integer value at index 0 to the same Integer list (i).

换句话说,为什么编译器不知道通配符类型的两种用法List<?>

i.set(0, i.get(0));

引用相同的实际类型?

嗯,这需要编译器知道 i对于表达式的两次计算都包含相同的实例。自 i甚至不是最终的,编译器必须检查是否 i可能已经在评估两个表达式之间分配了。这样的分析只对局部变量很简单(谁知道调用的方法是否会更新特定对象的特定字段?)。这在编译器中增加了相当多的额外复杂性,但很少显示出好处。我想这就是为什么 Java 编程语言的设计者通过指定相同通配符类型的不同使用具有不同的捕获来使事情变得简单。

关于Java 泛型 : Wildcard capture misunderstanding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372162/

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