0

我在使用 TreeSet 对我的 HashMap 进行排序时遇到问题。以下是我拥有的代码:

private static HashMap<OddMove, Integer> sortHashMap(
        HashMap<OddMove, Integer> hm) {
    Map<OddMove, Integer> tempMap = new HashMap<OddMove, Integer>();
    for (OddMove wsState : hm.keySet()) {
        tempMap.put(wsState, hm.get(wsState));
    }

    List<OddMove> mapKeys = new ArrayList<OddMove>(tempMap.keySet());
    List<Integer> mapValues = new ArrayList<Integer>(tempMap.values());
    HashMap<OddMove, Integer> sortedMap = new LinkedHashMap<OddMove, Integer>();
    TreeSet<OddMove> sortedSet = new TreeSet<OddMove>(mapKeys);
    Object[] sortedArray = sortedSet.toArray();
    int size = sortedArray.length;
    for (int i = 0; i < size; i++) {
        sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
                (Integer) sortedArray[i]);
    }
    return sortedMap;
}

以下是我得到的错误:

ABORTING: Exception in odd.UEPlayer3.choseMove()
java.lang.ClassCastException: odd.OddMove cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.AbstractCollection.addAll(AbstractCollection.java:334)
at java.util.TreeSet.addAll(TreeSet.java:312)
at java.util.TreeSet.<init>(TreeSet.java:160)
at odd.UEPlayer3.sortHashMap(UEPlayer3.java:196)
at odd.UEPlayer3.chooseMove(UEPlayer3.java:101)
at boardgame.Client.playMove(Client.java:109)
at boardgame.Client.processMessage(Client.java:86)
at boardgame.Client.clientLoop(Client.java:177)
at boardgame.Client.run(Client.java:73)
at java.lang.Thread.run(Thread.java:722)

非常感谢一些帮助

4

1 回答 1

0

我猜 OddMove 是您编写的自定义类。如果是这种情况,您需要更新它以实现Comparable接口。

于 2013-04-08T23:15:08.400 回答