[英]add (List<? extends Z>) where Z is an interface . Class B extends A implements Z why cant we call add() with a List<A>
Interface Z{}
Consider a simple interface Z as declared above.考虑上面声明的简单接口 Z。
Class A{}
A simple class A as declared above.一个简单的 class A 如上所述。
Class B extends A implements Z{}
Class B extends class A and implements interface Z Class B 扩展 class A 并实现接口 Z
class Test{
static void add(List<? super Z>){}
public static void main(String[] args){
List<A> aaa= new ArrayList<>();
add(aaa); //Gives error here
}
}
The add method in above test class has a parameter List so as far as i know i can call it with alist of type Z or with a list of type super class of implementation class of Z.上述测试 class 中的添加方法有一个参数列表,据我所知,我可以使用 Z 类型的列表或 Z的实现 class 的超级 class类型的列表来调用它。
class B is an implementation of Z but is also a child of A so class A satisfies the condition above.It is a super class of (class B) implementation class of Z(class B). class B is an implementation of Z but is also a child of A so class A satisfies the condition above.It is a super class of (class B) implementation class of Z(class B).
So when i call add() with an ArrayList why does it give an error.因此,当我使用 ArrayList 调用 add() 时,为什么会出现错误。
Imagine this is the method body of add
.想象一下这是
add
的方法体。 This compiles fine:这编译得很好:
static void add(List<? super Z> list){
list.add(new Z() {}); // Fine.
}
Also, this compiles fine.此外,这编译得很好。
List<A> aaa= new ArrayList<>();
// ... Something.
A a = aaa.get(0);
Now, what if the ... Something
is:现在,如果
... Something
是:
add(aaa); // Compiler error!
What would happen if that compiler error didn't happen?如果没有发生该编译器错误会发生什么? A
ClassCastException
on the A a = aaa.get(0);
A
A a = aaa.get(0);
上的ClassCastException
line, because it's an instance of some subclass of Z
that's not A
.行,因为它是
Z
的某个子类的实例,它不是A
。
Try it, by invoking add((List) aaa)
.通过调用
add((List) aaa)
来尝试一下。
This is why the compiler stops you doing it.这就是编译器阻止你这样做的原因。
List<? super Z>
List<? super Z>
is a list to which it's safe to add instances of Z
, or any subclass. List<? super Z>
是一个列表,可以安全地向其中添加Z
或任何子类的实例。 List<A>
is a list to which it's safe to add instances of A
, or any subclass, or null; List<A>
是一个列表,可以安全地向其中添加A
或任何子类或 null 的实例; and anything you retrieve from the list will be an A
, a subclass, or null.您从列表中检索到的任何内容都将是
A
、子类或 null。 Some instances of Z
aren't instances of A
. Z
的某些实例不是A
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.