尝试编译以下通用映射排序函数时,我遇到了以下错误:
"The method compareTo(V) is undefined for the type V"
请帮助让这个工作起来!
public class CollectionsPlus<K,V> {
/**
* Sort map by value
* @param map
* @return
*/
public static<K,V> Map<K, V> sortMapByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
map.entrySet());
Collections.sort(list,
new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1,
Map.Entry<K, V> o2) {
return (o2.getValue().compareTo(o1.getValue()));
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
Map.Entry<K, V> entry = it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
V extends Comparable<? super V>
。 - newacctCat
是Animal implements Comparable<Animal>
的子类:如果你的方法无法对Map<Object, Cat>
按值进行排序。但是,如果你将该方法声明为V extends Comparable<? super V>
,那么你现在可以通过值来排序该 Map,因为Cat
实现了Comparable<Animal>
,即 *Comparable<Something super Cat>
*。 - assylias