如何在 Java 中使用 TreeMap 時修復 java.lang.ClassCastException?


TreeMap 是 Java 集合框架的一個類,它實現了 NavigableMap 介面。它以樹結構儲存對映的元素,並提供了一種有效的替代方案,以排序順序儲存鍵值對。請注意,在建立 TreeMap 物件時,必須使用 Comparable 介面或 Comparator 介面,以便我們可以維護其元素的排序順序,否則,我們會遇到 java.lang.ClassCastException。在本文中,我們將解釋如何使用 Comparable 和 Comparator 介面來修復 TreeMap 中的此 ClassCastException。

修復 TreeMap 中的 java.lang.ClassCastException

讓我們從一個示例程式開始討論,該程式將向我們展示 TreeMap 中的 ClassCastException。

示例 1

在下面的示例中,我們將嘗試在沒有 Comparable 和 Comparator 介面的情況下將自定義類物件新增到 TreeMap,以表明 Java 編譯器會丟擲 java.lang.ClassCastException。

import java.util.*;
public class TrMap {
   String item;
   int price;
   TrMap(int price, String item) {
	// this keyword shows these variables belong to constructor
      this.item = item; 
      this.price = price;
   }
	// method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   public static void main(String[] args) {
      // Declaring collection TreeMap
     TreeMap<TrMap, Integer> obj = new TreeMap<>();
      // Adding object to the obj map
      obj.put(new TrMap(495, "TShirt"), 1);
      obj.put(new TrMap(660, "Shirt"), 2);
      // printing details obj map
      System.out.println("Elements of the map: " + obj);
   }
}

輸出

Exception in thread "main" java.lang.ClassCastException: class TrMap cannot be cast to class java.lang.Comparable (TrMap 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 TrMap.main(TrMap.java:18)

如何使用 Comparable 介面修復 java.lang.ClassCastException

讓我們從介紹 Comparable 介面開始討論。

Comparable 介面

當我們希望按其自然順序對自定義物件進行排序時,此介面很有用。例如,它按字典順序對字串進行排序,按數字順序對數字進行排序。此介面位於 'java.lang' 包中。通常,在此包中定義的類和介面預設情況下可供我們使用,因此無需顯式匯入此包。

語法

class nameOfclass implements Comparable<nameOfclass>

這裡,class 是建立類的關鍵字,implements 是啟用使用介面提供的功能的關鍵字。

compareTo()

Comparable 介面僅定義了一個名為 'compareTo' 的方法,可以覆蓋該方法以對物件集合進行排序。它提供了比較類物件與自身的功能。當“此”物件等於傳遞的物件時,它返回 0;如果“此”物件更大,則返回正值,否則返回負值。

語法

compareTo(nameOfclass nameOfobject);

示例 2

以下示例演示了在修復 ClassCastException 中使用 Comparable 的方法。

方法

  • 建立一個實現 Comparable 介面的類 'TrMap'。在其中,宣告兩個變數並定義此類的建構函式以及兩個引數 'item' 和 'price',型別分別為字串和雙精度數。

  • 接下來,我們將使用 'toString()' 方法將物件的資料轉換為字串。然後,定義 'compareTo' 方法以及作為引數的 'TrMap' 類物件,以將“此”物件與新建立的物件進行比較。

  • 現在,在 main() 方法中,宣告一個名為 'obj' 的 TreeMap 的 'TrMap' 類物件,並使用名為 'put()' 的內建方法將物件的詳細資訊儲存到其中。'item' 是鍵,其對應值為 'price'。

  • 最後,在 for-each 迴圈內使用 'keySet()' 方法檢索和列印與鍵關聯的值。

import java.util.*;
import java.lang.*;
public class TrMap implements Comparable<TrMap> {
   String item;
   int price;
   TrMap(String item, int price) {
	// this keyword shows these variables belong to constructor
      this.item = item; 
      this.price = price;
   }
	// method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   public String getName() {
      return this.item;
   }
   // overriding method
   public int compareTo(TrMap comp) {
      return this.item.compareTo(comp.item);
   }
   public static void main(String[] args) {
      // Declaring collection TreeMap
      TreeMap<String, TrMap> obj = new TreeMap<>();
      // Adding object to the obj map
      TrMap obj1 = new TrMap("TShirt", 495);
      obj.put(obj1.getName(), obj1);
      TrMap obj2 = new TrMap("Shirt", 660);
      obj.put(obj2.getName(), obj2);
      TrMap obj3 = new TrMap("Kurti", 455);
      obj.put(obj3.getName(), obj3);
      // printing details obj map
      System.out.println("Elements of the map: ");
      for (String unKey : obj.keySet()) {
         System.out.println(obj.get(unKey));
      }
   }
}

輸出

Elements of the map: 
Item: Kurti, Price: 455
Item: Shirt, Price: 660
Item: TShirt, Price: 495

如何使用 Comparator 修復 java.lang.ClassCastException

首先,讓我們介紹 Comparator 介面。

Comparator

顧名思義,它用於比較某些東西。在 Java 中,Comparator 是一個介面,用於對自定義物件進行排序。我們可以在其名為 'compare()' 的內建方法中編寫我們自己的邏輯來對指定的物體進行排序。此方法將兩個物件作為引數,然後返回一個整數值。透過此整數值,Comparator 決定哪個物件更大。

語法

class nameOfComparator implements Comparator< TypeOfComparator >() {
	compare( type object1, type object2 ) {
		// logic for comparison
	}
}    

示例 3

以下示例說明了在修復 ClassCastException 中使用 Comparator 的方法。

方法

  • 首先,匯入 'java.util' 包,以便我們可以使用 TreeSet。

  • 建立一個類 'TrMap'。在其中,宣告兩個變數並定義此類的建構函式以及兩個引數 'item' 和 'price',型別分別為字串和整數。

  • 接下來,我們將使用 'toString()' 方法將物件的資料轉換為字串。

  • 然後,定義另一個類 'Comp',它實現了 Comparator 介面,並在其中使用 'compare()' 方法以升序對 TreeMap 進行排序。

  • 在 'main()' 方法內部,透過傳遞 'Comp' 類的例項來建立 TreeMap 集合,以便對其進行排序。

  • 最後,使用 'put()' 方法將一些元素儲存到 TreeMap 集合中,然後列印結果。

import java.util.*;
class TrMap {
   String item;
   int price;
   TrMap(int price, String item) {
	// this keyword shows these variables belong to constructor
      this.item = item; 
      this.price = price;
   }
	// method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   public String getName() {
      return this.item;
   }
}
// use of comparator interface
class Comp implements Comparator<TrMap> {
   // logic to sort
   public int compare(TrMap i, TrMap j) {
      if(i.price > j.price) {
         return 1;
      } else {
         return -1;
      }
   }
}
public class Example2 {
   public static void main(String[] args) {
      // Declaring collection TreeMap
      TreeMap<TrMap, Integer> obj = new TreeMap<>(new Comp());
      // Adding object to the obj map
      obj.put(new TrMap(495, "TShirt"), 1);
      obj.put(new TrMap(660, "Shirt"), 2);
       // printing details obj map
      System.out.println("Elements of the map: " + obj);
   }
}

輸出

Elements of the map: {Item: TShirt, Price: 495=1, Item: Shirt, Price: 660=2}

結論

在本文中,我們首先定義了 TreeMap 類,然後介紹了 TreeMap 中的 ClassCastException。在下一節中,我們討論了 Comparator 和 Comparable 介面,它們可以幫助修復此 ClassCastException。然後,我們看到了三個示例程式,它們顯示了 ClassCastException 以及如何修復此異常。

更新時間: 2023 年 7 月 20 日

329 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.