Exception in thread "main" java.lang.ClassCastException: Item cannot be cast to java.lang.Comparable
代碼中使用 TreeSet 存儲 Item 對象:
SortedSet oo = new TreeSet<>();
oo.add(new Item("afang", 1011));
TreeSet 默認要求元素實現 Comparable 接口(自然順序),或在構造時提供 Comparator。此處 Item 類未實現 Comparable,且首個 TreeSet 構造未傳比較器,導致插入時嘗試將 Item 強轉為 Comparable 失敗。
class Item implements Comparable<Item> {
private String description;
private int id;
public Item(String aDes, int aId) {
description = aDes;
id = aId;
}
public String getDescription() { return description; }
public int getId() { return id; }
@Override
public int compareTo(Item other) {
// 例如按 id 排序
return Integer.compare(this.id, other.id);
}
}
之後可直接使用 new TreeSet<>()。
SortedSet<Item> sortedByDes = new TreeSet<>(new Comparator<Item>() {
@Override
public int compare(Item a, Item b) {
return a.getDescription().compareTo(b.getDescription());
}
});
注意:首個 TreeSet oo = new TreeSet<>(); 仍會報錯,必須改為帶比較器的構造,或讓 Item 實現 Comparable。
Comparable。Comparator 策略模式。TreeSet<Item> 能在編譯期發現類型不匹配,養成習慣。