-1

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?

Savior
  • 3,225
  • 4
  • 24
  • 48
  • 2
    `List extends T>` means any `List` holding types of sub-classes of `T`. Where `List` is self-explanatory. – nabster May 13 '20 at 17:34
  • 3
    I recommend reading https://docs.oracle.com/javase/tutorial/java/generics/index.html – nabster May 13 '20 at 17:35
  • Thank you for your answer, but I'm really confused because I didn't find a point to use List extends T> over List on this particular case ( ignore any kind of implementation ). – Pedro Henrique Silva Almeida May 13 '20 at 17:56
  • Pedro Henrique Silva Almeida try reading my answer and see if it helps you explain the concept of [here](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)) and [here](https://stackoverflow.com/questions/1163465/covariance-and-contravariance-in-programming-languages) – nabster May 25 '20 at 07:10

1 Answers1

1

<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)

Ceremonial example:

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) {}
Community
  • 1
  • 1
nabster
  • 1,561
  • 2
  • 20
  • 32