Joshua Bloch came up with the PECS, which says the rule when to use ? extends T
and ? super T
. If you think about PECS in terms of Collections framework, then it is very straightforward. If you add values to the data structure, use ? super T
. If you read from the data structure, use ? extends T
.
for instance:
public class Collections {
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (int i = 0; i < src.size(); i++)
dest.set(i, src.get(i));
}
}
If I check the signature of
public static <T> void sort(List<T> list, Comparator<? super T> c)
I see Comparator uses ? super
, so it should be a consumer. Looking at the code, comparator c is only used to produce stuff because it is asked the logic of comparing.
On one hand, I understand why it is a super because as a developer I want to use comparators of class T
and also comparators of super class T
because objects of T
is also of type super classes of T
. But when I try to think in terms of PECS, I fail to understand.
Does PECS only hold for Collections framework? If not, Can someone explain to me what does comparator consume in Collections.sort
?