我在使用 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)
非常感谢一些帮助