0

Hi I have that error:

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

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

The class Car extends the class Vehicle. The Truck also extends Vehicle. I have to create the Vehicle class 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


}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
bb88
  • 1
  • 2

1 Answers1

1

That doesn't compile because List<Car> is not a subtype of Iterable<Vehicle>.

It is, however, a subtype of Iterable<? extends Vehicle>. This is called covariance.

public static void print(Iterable<? extends Vehicle> it){
    for(Vehicle v: it) System.out.println(v);
}

You could also choose to make the method generic.

public static <A extends Vehicle> void print(Iterable<A> it){
    for(Vehicle v: it) System.out.println(v);
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137