【发布时间】:2014-04-03 15:15:33
【问题描述】:
我正在尝试对java.util.Map 进行如下排序。
public final class SortMapByValue <K, V extends Comparable<? super V>> implements Comparator<Map.Entry<K, V>>
{
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortedMap.entrySet());
Collections.sort(list); //Compiler error here.
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
如代码中所述,它发出如下编译时错误。
no suitable method found for sort(List<Entry<K,V>>)
method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
method Collections.<T#2>sort(List<T#2>) is not applicable
(inferred type does not conform to declared bound(s)
inferred: Entry<K,V>
bound(s): Comparable<? super Entry<K,V>>)
where K,V,T#1,T#2 are type-variables:
K extends Object declared in method <K,V>sortMapByValue(Map<K,V>)
V extends Comparable<? super V> declared in method <K,V>sortMapByValue(Map<K,V>)
T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
这也可以在sortMapByValue()方法中按如下方式完成。
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
但是,相反,我想按照这种方式修复错误(避免使用此匿名比较器)。如何修复该错误?
【问题讨论】:
-
您有一个
List的Entry。Entry类没有实现Comparable。但是,Collections.sort(..)需要实现Comparable的某种类型的List。 -
所以你有无法编译的代码和完美运行的代码。有效的代码的问题是你想使用不能编译的代码,而不能编译的代码的问题是你想让它编译。我有这个权利吗?
-
您需要将比较器传递给Collections.sort,例如像Collections.sort(list, new SortMapByValue());
-
有可能因为不清楚你在问什么而被关闭,真的吗? :)