I would like to know what does the declaration of the following method mean:
<T> T method(List<? extends T>) {...}
This method would be the same if List<? extends T>
becomes List<T>
? If not, why?
I would like to know what does the declaration of the following method mean:
<T> T method(List<? extends T>) {...}
This method would be the same if List<? extends T>
becomes List<T>
? If not, why?
<T> T method(List<? extends T>) {...}
means this method can accept an Object
that meets this criteria: List<? extends T>
where ?
represents a sub-class that is-A T
.
Note: List<T>
or List<? extends T>
or List<? super E>
or List<Integer>
or List<Car>
are all individual objects. (Yes, List
is a container (data structure) that further holds 1-to-many objects of its generic type i.e. T, E, Integer, Car
etc above)
Say you have a class structure as:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
then you have a method accepting container (data structure) like
public void updatePets (List<Animal> myPetsList) {}
When you try to pass List<Dog>
, then you will get a compile error. Not allowed.
Because object -> List<Dog>
is not same as object -> List<Animal>
. However, object -> List<Dog>
can be same as object -> List<? extends Animal>
. Do not confuse Animal
and List<Animal>
as same objects. These are two separate type of objects; one is user defined while other is defined by Java lang List
specifying a generic object type it can hold.
So your fixed method signature will become:
public void updatePets (List<? extends Animal> myPetsList) {}