I noticed the specificaition for Collections.sort:
public static <T> void sort(List<T> list, Comparator<? super T> c)
Why is the ‘? super‘ necessary here? If ClassB extends ClassA, then wouldn’t we have a guarantee that a Comparator<ClassA> would be able to compare two ClassB objects anyway, without the ‘? super‘ part?
In other words, given this code:
List<ClassB> list = . . . ; Comparator<ClassA> comp = . . . ; Collections.sort(list, comp);
why isn’t the compiler smart enough to know that this is OK even without specifying ‘? super‘ for the declaration of Collections.sort()?
Josh Bloch had a talk at Google I/O this year, called Effective Java Reloaded, which you may find interesting. It talks about a mnemonic called ‘Pecs’ (producer
extends, consumersuper), which explains why you use? extends Tand? super Tin your input parameters (only; never for return types), and when to use which.