Reputation: 495
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());}}
Upvotes: 1
Views: 558
Reputation: 3976
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.
Upvotes: 1
Reputation: 19185
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>
Upvotes: 4
Reputation: 13821
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.
Upvotes: 5