gpt4 book ai didi

java - 为什么我不能将 List 用作 Iterable

转载 作者:行者123 更新时间:2023-12-01 09:54:06 25 4
gpt4 key购买 nike

嗨,我有这个错误:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com