来自 this Oracle Java 教程:
The WildcardError example produces a capture error when compiled:
public class WildcardError {
void foo(List<?> i) {
i.set(0, i.get(0));
}
}
在此错误演示之后,他们使用辅助方法解决了问题:
public class WildcardFixed {
void foo(List<?> i) {
fooHelper(i);
}
// Helper method created so that the wildcard can be captured
// through type inference.
private <T> void fooHelper(List<T> l) {
l.set(0, l.get(0));
}
}
首先,他们说列表输入参数 ( i
) 被视为 Object
:
In this example, the compiler processes the
i
input parameter as being of type Object.
那为什么 i.get(0)
不返回 Object
?如果它已经这样传入了?
此外,使用 <?>
的意义何在?什么时候你必须使用辅助方法使用 <T>
.直接用T
会不会更好可以推断出哪些?
最佳答案
List<?>
确实意味着未知类型的对象列表,它与 List<Object>
不同.
因为我们不知道i.get(0)
的列表结果中元素的类型被 Java 视为 Object
, 你不能添加 Object
至 List<?>
.如果您的 Java 可以更智能,但代码更复杂,请使用 <?>
通配符很容易使其成为非类型安全的。
关于java - 捕获 Java 泛型中的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340474/