I'll post a single link here: Collections.sort()
. There have been many posts on SO with regards to the PECS paradigm, including this one. In my own personal code, I use generics quite a lot, but have only ever had the use of the P part (that is, <X extends SomethingElse>
).
Collections.sort
expects as its generics argument a <T extends Comparable<? super T>>
. I fail to see where the super
kicks in in there. Do you have a concrete example of why this is necessary?
While I am at it, I am deeply afraid that I don't understand the full implications of P either... I have read many, many links, without having had a clear, obvious proof that P is P and C is C...
EDIT As to the may already have an answer here": no, sorry. I have read this link, and many others on SO. This still does not tell me the core mechanism behind it all. The two answers given to me so far give me hints, in fact more so than all the links I could find so far.
E.g.
So "super" here allows to reuse MyNumberComparator for both sorting Integers and sorting Longs.
Try to create a List of Number :
Now try to sort it :
Looking at the generic argument
<T extends Comparable<? super T>>
, it equivalent in this case to<Number extends Comparable<? super Number>>
. However the Number class doesn't implement such a comparator. Hence the code does'nt compile and it forces you to create your own one.Say you have a class
Animal
, which is comparable to allAnimal
s:Now let's say you have a class
Dog
, which extendsAnimal
:Now the question is, can
Dog
compare to anotherDog
? (i.e. can you domyDog.compareTo(yourDog)
) The answer is of course. ADog
, as anAnimal
, is comparable to allAnimal
s, includingDog
s (as well asCat
s).However,
Dog
does not implementComparable<Dog>
, so a boundT extends Comparable<T>
would not work forT = Dog
.But for sorting all we care is that the type can compare to itself (which
Dog
can do). So the suitable least restrictive bound isT extends Comparable<? super T>
, which does work forDog
.