【发布时间】:2012-01-21 23:46:53
【问题描述】:
我有一个hashmap<CustomObject,Integer>,我想比较每个条目中的整数(值)。所以,基本上我想按它们的Integer 值按降序对我的值进行排序。我有一个Comparator,其中包含以下内容...
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 传递到 TreeMap..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 是一个自定义对象。
我想我误解了比较器的工作原理。我做错了什么?我将如何比较这两个 Integer 值?
编辑
只是为了澄清我实际上想要做什么......
我想比较链接到 CustomObject 的整数。我无法将密钥设为整数,因为这些整数可能不是唯一的。我要比较它们,因为我想根据它们的 Integer 值按降序对我的集合进行排序。
【问题讨论】:
-
抛出异常的代码在哪里??
-
问题是地图的比较器比较的是键,而不是值。除了做一个反向映射,然后检查它,然后将结果插入 LinkedHashMap 之外,我没有看到任何解决您的问题的方法。不是你想要的,我希望......
-
@SJuan76 我已经更新了我的代码以反映这一点
-
@fge 您建议根据键值对中的整数值对集合进行排序的最佳方法是什么?
-
好吧,我刚刚发现了这个:*.com/questions/109383/…