繁体   English   中英

添加(列表<!--? extends Z--> ) 其中 Z 是一个接口。 Class B 扩展 A 实现 Z 为什么我们不能用 List 调用 add()<a></a>

[英]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{}

考虑上面声明的简单接口 Z。

Class A{}

一个简单的 class A 如上所述。

 Class B extends A implements 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
} 
}

上述测试 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).

因此,当我使用 ArrayList 调用 add() 时,为什么会出现错误。

想象一下这是add的方法体。 这编译得很好:

static void add(List<? super Z> list){
  list.add(new Z() {});  // Fine.
}

此外,这编译得很好。

List<A> aaa= new ArrayList<>();
// ... Something.
A a = aaa.get(0);

现在,如果... Something是:

add(aaa);  // Compiler error!

如果没有发生该编译器错误会发生什么? A A a = aaa.get(0);上的ClassCastException 行,因为它是Z的某个子类的实例,它不是A

通过调用add((List) aaa)来尝试一下。

这就是编译器阻止你这样做的原因。 List<? super Z> List<? super Z>是一个列表,可以安全地向其中添加Z或任何子类的实例。 List<A>是一个列表,可以安全地向其中添加A或任何子类或 null 的实例; 您从列表中检索到的任何内容都将是A 、子类或 null。 Z的某些实例不是A实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM