我有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