Java 转换列表时的ClassCastException<;地图<;字符串,双>&燃气轮机;到TreeSet<;地图<;字符串,双>&燃气轮机;

Java 转换列表时的ClassCastException<;地图<;字符串,双>&燃气轮机;到TreeSet<;地图<;字符串,双>&燃气轮机;,java,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 =

我似乎无法理解为什么使用以下代码获得此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 )
}

如果您能深入了解为什么会发生这种情况,我们将不胜感激。谢谢

TreeSet
希望您为其元素类型传递一个
比较器,或为其元素实现
可比较的
<代码>映射
未实现
可比
,并且您尚未提供
比较器


但是,如果您使用
HashSet
,它将立即生效,因为
Map
有一个指定的
hashCode()
实现。

为什么要使用
TreeSet
?如果你必须使用它,你必须提供一种方法来比较
Map
。在我的项目中,我使用TreeSet来维护非重复项的排序顺序。我应该使用不同的东西吗?那么,您希望基于什么对
树集
中的地图进行排序?标题有误导性我将标题从集合更改为树集。
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);
}
    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)