2016-05-22 9 views
0

こんにちは、私はそのエラーを持っている:List <Truck>をIterable <Vehicle>として使用できないのはなぜですか?

incompatibles types: List<Car> cannot be converted to Iterable<Iterator> 

incompatibles types: List<Truck> cannot be converted to Iterable<Iterator> 

クラスの車は、クラスの車を拡張します。トラックはまた、車両を拡張します。 Vehicleクラスiterableを作成する必要がありますか? List<Car>ので、コンパイルされません

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

これにジェネリックを使用できます。 https://ideone.com/kTB71Y –

+0

を参照してくださいこの 'print(Iterable it)'をこの 'print(List it)' –

+0

に変更してくださいhttp://stackoverflow.com/questions/933447/how-do-あなたのサブキャストのリストのスーパータイプのリスト –

答えて

1

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); 
} 
+0

これは私にとって新しかったです、あなたに感謝@クリスマス - マーティン! –

関連する問題