Java Generic type : difference between List <? extends Number> and List <T extends Number>

Basic difference is if you use T extends Number then you can refer to the type T:
list.add((T) new Integer(40));

Where as if you use ? extends Number then you can not refer to the type, but you can still say:
((List<Integer>)list).add((int) s);


In isolation, there isn't much difference. However, two instances of List<? extends Number> in a single context are completely unrelated, while two instances of List<T extends Number> in a single context refer to the same T and the same interface.

public void addAll(List<? extends Number> to, List<? extends Number> from) {
    for (Number n: from) {
        to.add(n);
    }
}

This method fails because n can't be added to to, and also failed because the member types of from and to can be completely different.

public <T> void addAll(List<T extends Number> to, List<T extends Number> from) {
    for (T n: from) {
        to.add(n);
    }
}

This method compiles fine. It isn't necessary; Collections has a better version, but it will run without error.

Tags:

Java