- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
阅读 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/
我是一名优秀的程序员,十分优秀!