我的 HashMap 中有两个数组,我想根据 timeStampArray 中的时间对averageValueArray 中存储的值进行排序。我正在使用 TreeMap
但收到 ClassCastException
,它表示 ArrayList 不具有可比性。
这就是我正在做的事情:
Map<List<Date>,List<Double>> sortMap = new HashMap<List<Date>,List<Double>>();
sortMap.put(timeStampArray, averageValueArray);
for (Map.Entry entry : sortMap.entrySet()) {
System.out.println("Key = " + entry.getKey());
System.out.println(" Value = " +entry.getValue());
}
System.out.println("Unsort Map......");
printMap(sortMap);
System.out.println("Sorted Map......");
TreeMap<List<Date>,List<Double>> treeMap = new TreeMap<List<Date>,List<Double>>(sortMap);
for (Map.Entry entry : treeMap.entrySet()) {
System.out.println("Key = " + entry.getKey());
System.out.println(" Value = " +entry.getValue());
}
printMap(treeMap);
printMap 是:
public static void printMap(Map<List<Date>,List<Double>> map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());}}
最佳答案
正如错误消息所述,ArrayList
没有实现 TreeMap
所需的 Comparable
接口(interface)来对元素进行排序 map 。不过,您可以使用采用 Comparator
的构造函数来创建 TreeMap
,并根据您的排序规则实现比较器。
关于java - ClassCastException : java. util.ArrayList 不可比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16891173/