[英]Storing ArrayList<Integer> as key in TreeMap Java
我將arrayList作為鍵存儲在TreeMap中,但出現此異常
java.lang.ClassCastException:無法將java.util.ArrayList強制轉換為java.lang.Comparable
我將數組的內容復制到ArrayList並嘗試將該arrayList存儲為我在Map My Code中的鍵:
TreeMap< ArrayList<Integer> , Integer > bandsMap = new TreeMap< ArrayList<Integer> , Integer >();
ArrayList< Integer > erfcn = new ArrayList< Integer >();
for (int index = 0; index < frequencies.length; index++)
erfcn.add(frequencies[index]);
bandsMap.put( erfcn , band_number);
for (Integer value : bandsMap.values()) {
System.out.println("Value = " + value + "\n");
}
任何想法 ? 謝謝
樹形圖按排序順序維護其鍵。 ArrayList
類沒有定義任何順序,因此不能直接用作鍵。 您可以提供一個外部比較器來強加一個命令,但是您必須定義一個對您有意義的命令:
TreeMap<ArrayList<Integer>, Integer> bandsMap = new TreeMap<>(
new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> lst1, ArrayList<Integer> lst2) {
// return 1 if lst1 > lst2, 0 if equal, -1 if lst1 < lst2
}
});
另外,如果不必按任何特定順序維護密鑰,請改用HashMap
。
ArrayLists沒有實現Comparable ,因此您需要使用未排序的映射(例如HashMap) ,或告訴TreeMap如何使用此構造方法對ArrayLists
進行排序。
錯誤本身表明問題所在。 ArrayList類不實現java.lang.Comparable接口 ,並且TreeMap期望鍵實現可比較的接口。 因此,它導致了異常。
請參閱ArrayList文檔。
由於我們無法修改ArrayList,因此可以使用外部比較器使ArrayList用作TreeMap的鍵。 您只需要重寫其中的compare()方法。
您無法比較兩個列表,您必須將列表更改為其他結構,或者使用Comparable接口創建自己的列表。 好的解決方案也是將列表包裝在實現Comparable的新類中,並從接口僅實現此方法。
看看這個
public class Fruit implements Comparable<Fruit>{
public int compareTo(Fruit compareFruit) {
//your code here
}
}
還有這個鏈接。 希望能幫助到你。
如果您真的想使用ArrayList作為TreeMap中的鍵,那么您需要為其編寫Comparator並通過使用構造函數
在Tree中使用List作為鍵不是一個好主意,請檢查您的設計。
鑒於其他有關List
未實現Comparable的答案,您可以創建自己的類以充當TreeMap鍵,擴展ArrayList並實現Comparable:
class KeyList extends ArrayList<Integer> implements Comparable<ArrayList<Integer>> {
public int compareTo(ArrayList<Integer> list) {
//decide how to compare ArrayLists, then implement it here
return 0;
}
}
然后,您可以創建TreeMap:
new TreeMap<KeyList, Integer>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.