如何在Java中使用自定義比較器修復TreeSet中的java.lang.ClassCastException?
TreeSet是Java集合框架的一個泛型類,它實現了SortedSet介面。它以樹形結構儲存集合的元素。此外,所有元素都以排序的方式儲存,如果我們嘗試新增自定義類物件,則這些元素必須相互可比較,否則我們會遇到java.lang.ClassCastException。這裡,自定義類物件是指使用建構函式建立的使用者定義的物件。解決此ClassCastException的一種方法是使用自定義比較器。讓我們詳細討論一下。
TreeSet的一般語法如下所示
語法
TreeSet<TypeOfSet> nameOfSet = new TreeSet<>();
使用比較器修復TreeSet中的java.lang.ClassCastException
在本節中,我們將解釋如何使用自定義比較器來修復TreeSet中的ClassCastException。讓我們從比較器開始討論。
比較器
顧名思義,它用於比較某些東西。在Java中,Comparator是一個介面,用於排序自定義物件。我們可以在其內建方法“compare()”中編寫我們自己的邏輯來排序指定的物件。此方法將兩個物件作為引數,然後返回一個整數值。透過這個整數值,Comparator決定哪個物件更大。
語法
class nameOfComparator implements Comparator< TypeOfComparator >() {
compare( type object1, type object2 ) {
// logic for comparison
}
}
這裡,class是建立類的關鍵字,implements是啟用使用介面提供的功能的關鍵字。
示例1
在下面的示例中,我們將嘗試在沒有比較器的情況下將自定義類物件新增到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)
示例2
下面的示例說明了使用比較器修復ClassCastException的方法。
方法
首先,匯入'java.util'包,以便我們可以使用TreeSet。
建立一個類'ShopBag'。在其中,宣告兩個變數並定義此類的建構函式以及兩個引數'item'和'price',型別分別為字串和整數。
然後,定義另一個類'Comp',它實現了Comparator介面,並在其中使用'compare()'方法將TreeSet按升序排序。
在'main()'方法中,透過傳遞'Comp'類的例項來建立一個TreeSet集合,以便它可以被排序。
最後,使用'add()'方法將一些元素儲存到TreeSet集合中,然後使用foreach迴圈列印集合的元素。
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) {
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
結論
我們首先定義了TreeSet並介紹了TreeSet的ClassCastException。在下一節中,我們介紹了Comparator介面,它可以幫助修復ClassCastException。然後,我們討論了兩個示例程式,它們顯示了ClassCastException以及如何修復此異常。
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP