转换List <map <string,double>&gt;时出现ClassCastException to TreeSet <map <string,double>&gt; </map <string,double> </map <string,double>

时间:2014-03-02 19:00:06

标签: java

我似乎无法弄清楚为什么我会使用以下代码获取此ClassCastException:

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

因此,我尝试迭代test1并单独将映射放入test2,如下所示:

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

两者都提供了涉及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)

对于为什么会发生这种情况的任何见解都将非常感激。谢谢!

1 个答案:

答案 0 :(得分:8)

TreeSet希望您为其元素类型传递Comparator,或者为其元素传递ComparableMap未实现Comparable,您尚未提供Comparator

如果您使用HashSet,它就可以开箱即用,因为Map具有指定的hashCode()实现。