javagenericsextends

Why generic type is not applicable for argument extends super class for both?


Here is the problem that I have been being tried to find the solution.

We have two class definitions. One of two extends other one.

    class T{}
    class TT extends T{}

The requirement is that there should be a list keeps object extends T

    List<? extends T> list = new ArrayList<>();

But the problem occures when I try to put a TT object ( barely seems it is a subclass of T ) into the list.

    list.add(new TT());

Compilation Error Message

The method add(capture#2-of ? extends Cell) in the type List is not applicable for the arguments (Cell)


Solution

  • You can create a List<T> list = new ArrayList<T>(); directly, this can allow all subtypes of T into the list. This is actually little difficult to understand. when you declare it as

    List<? extends T> list = ...
    

    It means that it can allow any unknown subtypes of T into the list. But, from that declaration we cannot ensure which is the exact sub-type of T. so, we can only add null into it