Java泛型:按值排序地图
发布时间:2020-12-15 04:07:38 所属栏目:Java 来源:网络整理
导读:尝试编译以下函数来排序通用映射我得到此错误: "The method compareTo(V) is undefined for the type V" 请帮助完成这项工作! public class CollectionsPlusK,V { /** * Sort map by value * @param map * @return */ public staticK,V MapK,V sortMapByVa
尝试编译以下函数来排序通用映射我得到此错误:
"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实现Comparable.您可以通过以下方式明确要求:
public static<K,V extends Comparable<V>> Map<K,V> map) 或者,您可以将o1.getValue()和o2.getValue()强制转换为Comparable< V>. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |