Java泛型捕获列表<> [英] Java Generics Capture List<?>
问题描述
我在查看 Java泛型文档并找到这段代码,
public class WildcardError {
void foo(List<> l ){
//这给编译时错误
l.set(0,l.get(0));
$ / code $ / pre
我可以理解我们从 List<?>
并尝试将其设置为另一个 List<?>
。所以编译器给出了一个错误。我的问题是当2个列表不同时,这是有意义的,即 l.set(0,m.get(0))
这里列出 l 和 m
是不同的。但在上面的例子中, l
和 l
是相同的列表。为什么编译器不够聪明呢?是否很难实现它?
编辑:
我知道我可以通过辅助方法或使用 T
而不是?
。只是想知道为什么编译器不会为我做。
解决方案编译器报告错误,因为没有办法一般 - 它可以告诉两个表达式(在这种情况下 l
和 l
)是否引用相同的列表。
相关的,有些概括性的问题:
I was looking at the Java Generics documentation and found this piece of code,
public class WildcardError {
void foo(List<?> l) {
//This give a compile time error
l.set(0,l.get(0));
}
}
I can understand that we are fetching an element from a List<?>
and trying to set it to another List<?>
. So the compiler gives an error. My question is it makes sense when the 2 lists are different i.e. l.set(0, m.get(0))
here lists l
and m
are different. But in the above example, l
and l
are the same lists. Why isn't the compiler smart enough to see that? Is it hard to implement it?
Edit:
I am aware that I can fix it by a helper method or by using T
instead of a ?
. Just wondering why compiler doesn't do it for me.
解决方案 The compiler reports an error because there is no way -- in general -- that it can tell whether two expressions, (in this case l
and l
) refer to the same list.
Related, somewhat generalized, question:
这篇关于Java泛型捕获列表<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!