So what does it mean ?
The statement List<? extends Vehicle> means that you can pass any type of list that subtype of List and which is typed as Vehicle or some subtype of Vehicle. But you cannot add anything into the collection at all.
Now what is that? Why can’t we add anything into the collection?
(//which collection vehicle or bike or car???)
Lets consider this.
public void addVehicle(List<? extends Vehicle> vehicles){
vehicles.add(new Car());
}
The compiler stops you at the very moment. It doesn’t allow you to add anything while using ? extends. Why is that?
? extends allows us to pass any collection that is subytype of the method parameter which is typed as generic type of subtype of the generic type. i.e. we can pass an ArrayList<Vehicle> , ArrayList<Bike> or ArrayList<Car> to it.
But consider a scenario in which we are passing ArrayList<Bike> to addVehicle(List<? extends Vehicle>). In that case, if compiler didn’t stop us
(//i do not think compiler stopping right ??it is allowing vehicle, car, bike all 3 in case of extends???)
from adding into the collection, we would have added a Car into ArrayList<Bike>.
This is the scenario so ? extends doesn’t allow you to add into collection.
(//i thought we chose extends approach to allow vehicle and its subclasses right..i think compile time...but at run time type erasure kicks in which is bit unclear???)
But there is also a workaround for this. We can also pass a subtype collection and still be able to add into collection. We have to use the super keyword along with wildcard operator
//does it means we should always use super since extends has issues. Super is only for bike and its super classes right...it wont deal with subclasses at all??
It is *not* a list that can take anything that extends Vehicle !!
But you cannot add anything into the collection at all.
mechanic.addVehicle(vehicles); // compiles fine
mechanic.addVehicle(bikes); // compiles fine
mechanic.addVehicle(cars); // compiles fine
sai rama krishna wrote:
The method addVehicle(List<Vehicle>) in the type Mechanic is not applicable for the arguments (List<Bike>)
Don't get me started about those stupid light bulbs. |