2

If I have a basic class Pair with a generic constructor:

private T first;
private S second;

public Pair(Pair<T, S> p) {
    this(p.first, p.second);
}

like so, then what is the difference between this and this?

private T first;
private S second;


public Pair(Pair<? extends T, ? extends S> p) {
    this(p.first, p.second);
}

I understand that the second example is an upper bounded wildcard meaning that the Type can be T or any subclass of T but if I do something like:

Pair<Animal, Animal> animalPair = new Pair<>(new Cat("Tiddles"), new Dog("Rover"));

or:

Pair<Number, Number> numberPair = new Pair<>(2.97, 7545498865L);

then these arguments are subclasses of T and S anyway so the compiler doesn't complain with or without the ? extends part.

When would you use ? extends T instead of just T? Sorry if this has been asked before, I just can't seem to find an example where you would need to use it.

PumpkinBreath
  • 831
  • 1
  • 9
  • 22

0 Answers0