嗨,我有这个错误:
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
}
答案 0 :(得分:1)
由于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);
}