2
boolean addAll(Collection<? extends E> c);
boolean add(E e);

The param in Collection.addAll is Collection<? extends E>,I think it means all subclass of E can be use, but the param in Collection.add is E. I think it means only E class can be use.

So why the subclass of E can not be param in this method? Such as <T extends E> boolean add(T t);

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
sibo.wang
  • 65
  • 8
  • 5
    Anything that extends E is also an E. But, as generics are invariant, the same principle does not apply. – bcsb1001 Aug 09 '17 at 11:57
  • 4
    @bcsb1001 where invariance means that a `Collection` is not a `Collection`. See https://stackoverflow.com/q/2745265/3788176. (Provided for OP's benefit, not yours; it just follows from your comment :) ) – Andy Turner Aug 09 '17 at 12:02

1 Answers1

2

The upper bound wildcard is necessary for a Collection of type T. Let's take the following structure

class Animals{}
class Dog extends Animals{}
class Cat extends Animals{}

class Container<T>{
    void add(T t){};
    void addAll(Collection<T> t){};
}

And we instantiate it and use it like this

ArrayList<Dog> dogs = new ArrayList<>();
dogs.add(new Dog());

ArrayList<Cat> cats = new ArrayList<>();
cats.add(new Cat());

Container<Animals> animalContainer = new Container<>();
animalContainer.add(dogs.get(0)); // will work since add(T t)
animalContainer.addAll(cats); // will not work since addAll(Collection<T> t)

The reason why it will not work with addAll(Collection<T> t) is that the container will only accept the type T which is Animal, but since the cat list is of type Cat it violates the constraints.

Since Animal can be a Dog, Cat, AnyOtherConcreteAnimal. By changing it to an upper bound wildcard

void addAll(Collection<? extends T> t){};

You say that you expect an Collection with the concrete type of Animals and not only T which is Container<Animals>. And now this will work again

 animalContainer.addAll(cats); // will work since addAll(Collection<? extends T> t)
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107