比较HashMap和Objects

Ski*_*zit 1 java hashmap

我有一个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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过Hashmap调用以下代码行将我传递到TreeMap中Tmap.putAll(Hmap);.Tmap和Hmap定义为:

private HashMap<CustomObject,Integer> Hmap;
private TreeMap<CustomObject,Integer> Tmap;
Run Code Online (Sandbox Code Playgroud)

当我运行我的代码时,我得到了错误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);
Run Code Online (Sandbox Code Playgroud)

哪里o是CustomObject.

我想我误解了比较器是如何工作的......我做错了什么?我如何比较两个整数值?

编辑

只是为了澄清我实际上要做的事情......

我想比较链接到CustomObject的整数.我无法将关键字作为整数,因为这些整数可能不是唯一的.我要对它们进行比较,因为我想根据它们的Integer值按降序对我的集合进行排序.

Bjö*_*lex 5

您需要更改比较器以比较CustomObjects,而不是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));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,你需要告诉TreeMap使用你的比较器:

private Map<CustomObject,Integer> Tmap = 
    new TreeMap<CustomObject,Integer>(new Compare(HMap));
Run Code Online (Sandbox Code Playgroud)