2013-02-17 65 views
3

排序地图试图编译以下功能排序通用的地图我得到这个错误:Java泛型:由价值

"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; 
    } 
} 

回答

6

你需要有V实施Comparable。您可以通过书面形式明确要求它:

public static<K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> map) 

或者,您也可以施放o1.getValue()o2.getValue()Comparable<V>

+0

作品像魅力,谢谢你,@assylias! – 2013-02-17 17:03:01

+0

为获得最佳效果,请使用'V extends Comparable ' – newacct 2013-02-17 20:20:29

+0

它越来越隐蔽。当Java有一个体面的类型系统?不在我的一生中,我害怕:) – 2013-02-17 20:44:59