1

Why List.sort() use Comparator<? super E> instead of Comparator<? extends E> or just Comparator<E>?

If a List<E> contains elements of type E or its sub-types, Comparator should only expect type E or its sub-types, in its compare method call.

For example: For a list of type Integer, why would I need a Comaparator<Object> or Comparator<Number> when List<Integer> can only have Integer or its sub-type?

This is not a duplicate question, please read discussion in comment section.

John
  • 371
  • 3
  • 11
  • 1
    [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/q/2723397/2970947) – Elliott Frisch Apr 22 '19 at 02:33
  • I saw those pages, they explain PECS in terms of collection, but here sort method parameter is Comparator, which is not collection. – John Apr 22 '19 at 02:39
  • 1
    And what is `List`? – Elliott Frisch Apr 22 '19 at 02:40
  • @ElliottFrisch List is a collection. My question is regarding sort method in List interface. – John Apr 22 '19 at 02:42
  • 1
    And what are you going to `sort` (with the `sort` method in the `List` interface)? – Elliott Frisch Apr 22 '19 at 02:46
  • @ElliottFrisch I will be sorting that List of type Integer. Why would I ever pass a Comparator in that sort. I expect Comparator extends Integer> – John Apr 22 '19 at 02:51
  • You would not, but in some cases you might sort a `List` - then you need to compare `Cat`(s) and `Dog`(s) and `Goldfish`(s). – Elliott Frisch Apr 22 '19 at 02:52
  • So if Cat, Dog and Goldfish extends Pet. I can have a Comparator extends Pet>. Why would I need Pet super Pet> – John Apr 22 '19 at 02:56
  • 1
    Let's say you did have a `Comparator` that could compare any type of object. Wouldn't you want to be able to sort a list of integers with it? You sure would. Integers are objects, after all. A `Comparator` is an even smarter and more capable kind of comparator than one that *just* handles integers. This one can handle not just integers, but any old object! – John Kugelman Apr 24 '19 at 00:04
  • @JohnKugelman So super E> in List.sort's Comapartor exists to provide a generic comaparator in an application which one can pass around in application to sort lists of several types in same hierarchy. – John Apr 24 '19 at 02:07

0 Answers0