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?