ClassCastException:java.util.ArrayList不是Comparable

Spa*_*lug 0 java mapping hashmap treemap

我的Hash映射中有两个数组,我想根据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);
Run Code Online (Sandbox Code Playgroud)

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

Nil*_*lsH 5

正如错误消息所示,ArrayList没有实现对映射中元素进行排序Comparable所需的接口TreeMap.但是,您可以TreeMap使用构造函数创建Comparator代替,并根据您的排序规则实现比较器.