简体   繁体   中英

ClassCastException: java.util.ArrayList is not Comparable

I have two arrays in my Hash map and I want to sort the values stored in the averageValueArray according to the time in the timeStampArray. I am using TreeMap but I am getting ClassCastException which says that ArrayList is not comparable.

This is what I am doing:

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);

And the printMap is:

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());}}

As the error message says, ArrayList does not implement the Comparable interface that is required by TreeMap to do the ordering of the elements in the map. You can, however, create the TreeMap with the constructor that takes a Comparator instead, and implement the comparator according to your ordering rules.

From Java doc of TreeMap

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

List does not implements Comparable so you need to provide Comparator

I still can't figure out why are you using List . What you need can just be possible using TreeMap<Date, Double>

You need to use a comparator as the key of your tree map doesn't implement the Comparable interface.

There's a TreeMap constructor which accepts a custom Comparator and you can implement that with your custom logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM