我有一个 hashmap<CustomObject,Integer>
我想比较每个条目中的整数(值)。所以,基本上我想按他们的 Integer
对我的值(value)观进行排序值降序排列。我有一个 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
是一个 CustomObject。
我想我误解了比较器的工作原理..我做错了什么?我将如何比较这两个整数值?
编辑
只是为了澄清我实际上想做什么...
我想比较链接到 CustomObject 的整数。我无法将 key 设为整数,因为这些整数可能不是唯一的。我要比较它们是因为我想根据它们的整数值按降序对我的集合进行排序。
最佳答案
您需要更改比较器以比较 CustomObject
,而不是 Integers
:
class Compare implements Comparator<CustomObject>{
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(CustomObject left, CustomObject right){
return map.get(left).compareTo(map.get(right));
}
}
然后,您需要告诉 TreeMap
使用您的比较器:
private Map<CustomObject,Integer> Tmap =
new TreeMap<CustomObject,Integer>(new Compare(HMap));
关于java - 将 HashMap 与对象进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8534354/