嗨,我有一个错误:
incompatibles types: List<Car> cannot be converted to Iterable<Iterator>
incompatibles types: List<Truck> cannot be converted to Iterable<Iterator>class Car扩展了class Vehicle。卡车还延伸了车辆。我必须创建Vehicle类iterable??
public static void print(Iterable<Vehicle> it){
for(Vehicle v: it) System.out.println(v);
}
public static void main(String[] args) {
List<Car> lcotxe = new LinkedList<Car>();
List<Truck> lcamio = new LinkedList<Truck>();
print(lcotxe);//ERROR
print(lcamio);//ERROR
}发布于 2016-05-23 01:51:21
这不能编译,因为List<Car>不是Iterable<Vehicle>的子类型。
但是,它是Iterable<? extends Vehicle>的一个子类型。这称为covariance。
public static void print(Iterable<? extends Vehicle> it){
for(Vehicle v: it) System.out.println(v);
}您还可以选择使该方法成为泛型。
public static <A extends Vehicle> void print(Iterable<A> it){
for(Vehicle v: it) System.out.println(v);
}https://stackoverflow.com/questions/37377616
复制相似问题