I have a small program that is supposed to sort a map based on its values. Here is what I have so far:
public static <K, V extends Comparable< ? extends V>> Map<K, V>
sortByValues(final Map <K, V> mapToSort)
{
List<Map.Entry<K, V>> entries =
new ArrayList<Map.Entry<K, V>>(mapToSort.size());
entries.addAll(mapToSort.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>()
{
public int compare(
final Map.Entry<K, V> entry1,
final Map.Entry<K, V> entry2)
{
return entry1.getValue().compareTo(entry2.getValue());
}
});
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : entries)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
I want my generic value V to be comparable to anything that is either V or is a at least a subclass of V.
I get the following error for the code piece :
public static <K, V extends Comparable< ? extends V>>
Bound mismatch: The method compareTo(? extends V) of type V is not applicable for the arguments (V). The wildcard parameter ? extends V has no lower bound, and may actually be more restrictive than argument V
How can it be more restrictive?
If I change the declaration to:
public static <K, V extends Comparable< ? super V>>
then there is no error. But this is not what I want.
One workaround I have is that, I can change the declaration to:
public static <K, V extends Comparable<V>>
but doing this I lose the flexibility in that I cannot pass a Map whose value implements Comparable with a subclass of itself.
Apologies for such a long question. Thanks in advance.