gre*_*ell 2 java collections inheritance interface
我想弄清楚为什么这段代码不能编译.
我有接口A扩展的接口B.类C实现接口B.
当我调用一个接收A类单个对象的方法时,我可以传入一个C类型的对象,这很好.
当我调用一个接收类型为A的java.util.List的方法时,我无法传入类型为C的对象的java.util.List.Eclipse会生成以下错误:类型为Test1的方法addAList(List)不适用于参数(List)
源代码示例如下.
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public void addASingle(A a) {
return;
}
public void addAList(List<A> aList) {
return;
}
// **********************************
public static void main(String[] args) {
Test1 t = new Test1();
C c1 = new C();
List<C> cList = new ArrayList<C>();
cList.add(c1);
t.addASingle(c1); // allowed
t.addAList(cList); // The method addAList(List<Test1.A>)
// in the type Test1 is not applicable for the arguments (List<Test1.C>)
}
// **********************************
public static interface A {
}
public static interface B extends A {
}
public static class C implements B {
}
}
Run Code Online (Sandbox Code Playgroud)
JB *_*zet 14
A List<Car>
不是List<Vehicle>
.如果是,您可以执行以下操作:
List<Car> cars = new ArrayList<>();
List<Vehicle> vehicles = cars;
vehicles.add(new Bicycle());
Run Code Online (Sandbox Code Playgroud)
你会得到一个包含自行车的汽车列表.它会破坏通用集合的类型安全性.
您可能应该使用a List<? extends A>
而不是List<A>
.List<? extends A>
意思是:a List<some class which is A or which extends A>
.
归档时间: |
|
查看次数: |
99 次 |
最近记录: |