如何修復TreeSet中的java.lang.ClassCastException?
TreeSet是Java集合框架中的一個泛型類,它實現了SortedSet介面。它以樹形結構儲存集合的元素。此外,所有元素都以排序的方式儲存,如果我們嘗試新增自定義類物件,則這些元素必須可以相互比較,否則我們將遇到java.lang.ClassCastException。這裡,自定義類物件是指使用建構函式建立的使用者定義物件。為了修復TreeSet中的ClassCastException,我們可以使用Comparator介面或Comparable介面。讓我們詳細討論一下。
TreeSet的一般語法如下所示
語法
TreeSet<TypeOfSet> nameOfSet = new TreeSet<>();
修復TreeSet中的java.lang.ClassCastException
在本節中,我們將解釋如何使用Comparator和Comparable介面來修復TreeSet中的ClassCastException。讓我們從一個示例程式開始討論,該程式將向我們展示ClassCastException。
示例1
在下面的示例中,我們將嘗試在沒有Comparator和Comparable的情況下將自定義類物件新增到TreeSet,以顯示Java編譯器如何丟擲java.lang.ClassCastException。
import java.util.*; public class ShopBag { String item; int price; ShopBag(String item, int price) { // constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; } public static void main(String[] args) { // Declaring collection TreeSet TreeSet<ShopBag> trSet = new TreeSet<ShopBag>(); // Adding object to the collection trSet.add(new ShopBag("Rice", 59)); trSet.add(new ShopBag("Milk", 60)); // to print the objects for (ShopBag print : trSet) { System.out.println("Item: " + print.item + ", " + "Price: " + print.price); } } }
輸出
Exception in thread "main" java.lang.ClassCastException: class ShopBag cannot be cast to class java.lang.Comparable (ShopBag is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.TreeMap.compare(TreeMap.java:1569) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776) at java.base/java.util.TreeMap.put(TreeMap.java:785) at java.base/java.util.TreeMap.put(TreeMap.java:534) at java.base/java.util.TreeSet.add(TreeSet.java:255) at ShopBag.main(ShopBag.java:14)
如何使用Comparator修復java.lang.ClassCastException
首先,讓我們介紹Comparator介面。
Comparator
顧名思義,它用於比較某些東西。在Java中,Comparator是一個用於排序自定義物件的介面。我們可以在其名為“compare()”的內建方法中編寫我們自己的邏輯來排序指定的物件。此方法將兩個物件作為引數,然後返回一個整數值。透過這個整數值,Comparator決定哪個物件更大。
語法
class nameOfComparator implements Comparator< TypeOfComparator >() { compare( type object1, type object2 ) { // logic for comparison } }
示例2
下面的示例演示了在修復ClassCastException時使用Comparator。
方法
首先,匯入“java.util”包,以便我們可以使用TreeSet。
建立一個名為“ShopBag”的類。在其中,宣告兩個變數並定義該類的建構函式以及分別為字串和整數型別的兩個引數“item”和“price”。
然後,定義另一個實現Comparator介面的類“Comp”,並在其中使用“compare()”方法將TreeSet按升序排序。
在“main()”方法中,透過傳遞“Comp”類的例項來建立一個TreeSet集合,以便可以對其進行排序。
最後,使用“add()”方法將一些元素儲存到TreeSet集合中,然後使用for-each迴圈列印集合的元素。
import java.util.*; class ShopBag { String item; int price; ShopBag(String item, int price) { // constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; } } // use of comparator interface class Comp implements Comparator<ShopBag> { // logic to sort public int compare(ShopBag i, ShopBag j) { if(i.price > j.price) { // performing comparison return 1; } else { return -1; } } } public class Example2 { public static void main(String[] args) { // Declaring collection TreeSet TreeSet<ShopBag> trSet = new TreeSet<ShopBag>(new Comp()); // Adding object to the collection trSet.add(new ShopBag("Rice", 59)); trSet.add(new ShopBag("Milk", 60)); trSet.add(new ShopBag("Bread", 45)); trSet.add(new ShopBag("Peanut", 230)); trSet.add(new ShopBag("Butter", 55)); System.out.println("Objects of the collection: "); // to print the objects for (ShopBag print : trSet) { System.out.println("Item: " + print.item + ", " + "Price: " + print.price); } } }
輸出
Objects of the collection: Item: Bread, Price: 45 Item: Butter, Price: 55 Item: Rice, Price: 59 Item: Milk, Price: 60 Item: Peanut, Price: 230
如何使用Comparable介面修復java.lang.ClassCastException
讓我們從介紹Comparable介面開始討論。
Comparable介面
當我們想要按其自然順序排序自定義物件時,此介面很有用。例如,它按字典順序排序字串,按數字順序排序數字。此介面在“java.lang”包中可用。
語法
class nameOfclass implements Comparable<nameofclass>
這裡,class是建立類的關鍵字,implements是啟用使用介面提供的功能的關鍵字。
compareTo()
Comparable介面只定義了一個名為“compareTo”的方法,可以重寫該方法以排序物件集合。它提供了比較類物件與其自身的能力。當“this”物件等於傳遞的物件時,它返回0;如果“this”物件更大,則返回正值,否則返回負值。
語法
compareTo(nameOfclass nameOfobject);
示例3
下面的示例演示了在修復ClassCastException時使用Comparable。
方法
首先,匯入“java.util”包,以便我們可以使用TreeSet。
建立一個實現Comparable介面的類“ShopBag”。在其中,宣告兩個變數並定義該類的建構函式以及分別為字串和整數型別的兩個引數“item”和“price”。
定義“compareTo”方法以及作為引數的“ShopBag”類物件,以比較“this”物件與新建立的物件。
現在,在main()方法中,宣告一個名為“trSet”的TreeSet型別“ShopBag”類物件,並使用名為“add()”的內建方法將物件的詳細資訊儲存到集合中。
使用for-each迴圈列印集合的元素。
import java.util.*; public class ShopBag implements Comparable<ShopBag> { String item; int price; ShopBag(String item, int price) { // constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; } // overriding method public int compareTo(ShopBag comp) { if(this.price > comp.price) { // performing comparison return 1; } else { return -1; } } public String toString() { return "Item: " + this.item + ", Price: " + this.price; } public static void main(String[] args) { // Declaring collection TreeSet TreeSet<ShopBag> trSet = new TreeSet<ShopBag>(); // Adding object to the collection trSet.add(new ShopBag("Rice", 59)); trSet.add(new ShopBag("Milk", 60)); trSet.add(new ShopBag("Bread", 45)); trSet.add(new ShopBag("Peanut", 230)); trSet.add(new ShopBag("Butter", 55)); System.out.println("Objects of the collection: "); // to print the objects for (ShopBag print : trSet) { System.out.println("Item: " + print.item + ", " + "Price: " + print.price); } } }
輸出
Objects of the collection: Item: Bread, Price: 45 Item: Butter, Price: 55 Item: Rice, Price: 59 Item: Milk, Price: 60 Item: Peanut, Price: 230
結論
我們從定義TreeSet和介紹TreeSet的ClassCastException開始這篇文章。在下一節中,我們介紹了Comparator和Comparable介面,它們可以幫助修復ClassCastException。然後,我們討論了三個示例程式,這些程式顯示了ClassCastException以及如何修復此異常。