RyanS
RyanS

Reputation: 85

ClassCastException when converting List<Map<String,Double>> to TreeSet<Map<String,Double>>

I cannot seem to figure out why I get this ClassCastException with the following code:

public static void main(String[] args) {        

    Map<String,Double>          test0 = new TreeMap<String,Double>();
    test0.put("test", 1.);
    List<Map<String,Double>>    test1 = Arrays.asList(  test0 );

    Set<Map<String,Double>      test2 = new TreeSet<Map<String,Double>>( test1 )
}

So instead I try iterating through test1 and individually placing the maps into test2 as follows:

public static void main(String[] args) {        

    Map<String,Double>          test0 = new TreeMap<String,Double>();
    test0.put("test", 1.);
    List<Map<String,Double>>    test1 = Arrays.asList(  test0 );
    Set<Map<String,Double>>     test2 = new TreeSet<Map<String,Double>>();  

    for (Map<String,Double> mp : test1)
        test2.add(mp);
}

Both give the same exception involving Comparable:

    Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap 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 Delete.main(Delete.java:20)

Any insight into why this is happening would be greatly appreciated. Thanks!

Upvotes: 2

Views: 327

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198033

TreeSet expects you to either pass in a Comparator for its element type, or for its elements to implement Comparable. Map does not implement Comparable, and you haven't provided a Comparator.

It'd work out-of-the-box if you used a HashSet, though, since Map has a specified hashCode() implementation.

Upvotes: 8

Related Questions