我有hashmap<CustomObject,Integer>
,我想比較每個條目中的整數(值)。所以,基本上我想按降序排列我的值Integer
的值。我有一個Comparator
它由以下部分組成...將HashMap與對象比較
class Compare implements Comparator<Integer>{
Map<CustomObject,Integer> map;
/**
* Constructs our map
* @param map map to be sorted.
*/
public Compare(Map<CustomObject,Integer> map){
this.map = map;
}
/**
* Performs the comparison between two entries.
*/
public int compare(Integer one, Integer two){
if(map.get(one) <= map.get(two)){
return 1;
}else{
return 0;
}
}
}
我通過我的Hashmap
成樹形圖通過調用下面的代碼行.. Tmap.putAll(Hmap);
。凡TMAP和HMAP被定義爲:當我運行我的代碼
private HashMap<CustomObject,Integer> Hmap;
private TreeMap<CustomObject,Integer> Tmap;
我得到的錯誤Exception in thread "main" java.lang.ClassCastException: CustomObject cannot be cast to java.lang.Comparable
。
當我試圖從我的排序列表中提取一個值時,異常似乎會被調用。像這樣......
TreeMap<CustomObject,Integer> sorted = Tmap.putAll(hmap);
sorted.get(o);
其中o
是CustomObject。
我想我誤解了比較器的工作原理..我做錯了什麼?我如何比較兩個整數值?
編輯
只是爲了澄清什麼,我實際上是試圖做...
我想比較其鏈接到CustomObject整數。我無法使整數的關鍵,因爲這些整數可能不是唯一的。我想對它們進行比較,因爲我想根據它們的Integer值以降序對我的集合進行排序。
哪裏是拋出異常的代碼? – SJuan76 2011-12-16 12:50:07
問題是比較器的地圖比較鍵而不是值。除了執行反向映射外,我沒有看到任何解決方案,然後繼續,然後將結果插入到LinkedHashMap中。不是你想要的,我希望... – fge 2011-12-16 12:52:02