0

In the Java JDK, I noticed that there is a static method in the Map class:

public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K, V>> comparingByValue() {
    return (c1, c2) -> c1.getValue().compareTo(c2.getValue());
}

To my curiosity, I changed the code to:

public static <K, V extends Comparable<? extends V>> Comparator<Map.Entry<K, V>> comparingByValue() {
    return (c1, c2) -> c1.getValue().compareTo(c2.getValue());
}

The compiler gives error at this line:

return (c1, c2) -> c1.getValue().compareTo(c2.getValue());

Error: java: incompatible types: V cannot be converted to capture#1 of ? extends V

It maybe doesn't make sense to make V compare to an object of its subclass, but I'm confused that why compiler throws error in this case? Wildcard bounded generics should be inclusive right? Why compiler expects an object of subclass of V in the parameter of compareTo method?

souverlai
  • 43
  • 4
  • 2
    ` super V>` and ` extends V>` mean different things – take a look [here](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – Kaan Jan 22 '20 at 05:06
  • To get the understanding between `super` vs `extend` i use the following brain hack created by me: It is always difficult to **put/write** things than to **read** from, `super` signifies **superman** means he can write, so use ` super V>` when you need to add something and the left is ` extend V>` which just let you read only. **This is my brain mapping that i use, when to use `extend` vs `super` ** – Vishwa Ratna Jan 22 '20 at 06:01

1 Answers1

2

All that's really required is that every instance of V be comparable to every other instance of V (at least as far as the type system can tell; of course, it's always possible that the compareTo implementation enforces additional requirements at run-time).

V extends Comparable<? super V> ensures that that requirement is met: it means that instances of V are comparable to all instances of some supertype of V, which necessarily includes all instances of V. (Keep in mind that all instances of a type are also instances of all of its supertypes.)

V extends Comparable<? extends V>, by contrast, doesn't provide any useful guarantee; it means that instances of V can be compared to instances of some subtype of V, but that subtype may not be relevant at all.

ruakh
  • 175,680
  • 26
  • 273
  • 307