嗨,我有这个错误:
incompatibles types: List<Car> cannot be converted to Iterable<Iterator>
incompatibles types: List<Truck> cannot be converted to Iterable<Iterator>
Car 类扩展了 Vehicle 类。卡车还扩展了车辆。我必须创建可迭代的 Vehicle 类??
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
}
最佳答案
这无法编译,因为 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);
}
关于java - 为什么我不能将 List<Truck> 用作 Iterable<Vehicle>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37377616/