[英]ClassCastException when converting List<Map<String,Double>> to TreeSet<Map<String,Double>>
我似乎無法弄清楚為什么我使用以下代碼獲得此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)
任何有關為什么會發生這種情況的見解將不勝感激。 謝謝!
TreeSet
您為其元素類型傳遞Comparator
,或者為其元素傳遞Comparable
。 Map
沒有實現Comparable
,並且您沒有提供Comparator
。
但是,如果使用HashSet
,它可以開箱即用,因為Map
具有指定的hashCode()
實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.