首頁  >  文章  >  Java  >  使用Java中的TreeMap時如何解決java.lang.ClassCastException問題?

使用Java中的TreeMap時如何解決java.lang.ClassCastException問題?

王林
王林轉載
2023-08-20 23:55:101089瀏覽

使用Java中的TreeMap時如何解決java.lang.ClassCastException問題?

TreeMap是Java Collection Framework的一個類,實作了NavigableMap介面。它將地圖的元素儲存在樹狀結構中,並提供了一種有效的替代方法,以按排序順序儲存鍵值對。請注意,在建立TreeMap物件時,必須使用Comparable介面或Comparator介面之一,以便我們可以維護其元素的排序順序,否則,我們將遇到java.lang.ClassCastException。在本文中,我們將說明如何使用Comparable和Comparator介面來解決TreeMap中的ClassCastException問題

修復TreeMap中的java.lang.ClassCastException問題

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

Example 1

的中文翻譯為:

範例 1

在下面的範例中,我們將嘗試向TreeMap中新增自訂類別對象,而不使用Comparable和Comparator接口,以展示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);
   }
}

Output

的中文翻譯為:

輸出

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() 的翻譯為:

The Comparable interface defines only a single method named 'CompareTo' that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. returns power to compare the objects of a class to itself。 is equal to the passed object, a positive value if 'this' object is greater otherwise a negative value.

語法

compareTo(nameOfclass nameOfobject);

Example 2

的中文翻譯為:

範例2

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

方法

  • 建立一個實作Comparable介面的類別'TrMap'。在類別內部,宣告兩個變量,並定義一個帶有兩個參數的建構函數,參數類型分別為字串和雙精確度的'item'和'price'。

  • 進一步移動,我們將使用'toString()'方法將物件的資料轉換為字串。然後,定義'compareTo'方法,並將一個類別'TrMap'的物件作為參數,用於比較'this'物件和新建立的對象

  • 現在,在main()方法中,宣告一個名為'obj'的TreeMap類別的對象,並使用名為'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));
      }
   }
}

Output

的中文翻譯為:

輸出

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

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

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

比較器

如其名稱所示,它用於比較某些東西。在Java中,Comparator是一個接口,用於對自訂物件進行排序。我們可以在其內建的名為'compare()'的方法中編寫自己的邏輯來對指定的物件進行排序。此方法接受兩個物件作為參數,然後傳回一個整數值。透過這個整數值,Comparator決定哪個物件更大

語法

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

Example 3

的中文翻譯為:

範例 3

下面的範例示範了在修復ClassCastException時使用Comparator的方法。

方法

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

  • 建立一個名為 'TrMap' 的類別。在類別內部,宣告兩個變量,並定義一個建構函數,該構造函數有兩個參數 'item' 和 'price',分別是字串類型和整數類型。

  • 進一步移動,我們將使用 'toString()' 方法將物件的資料轉換為字串

  • 然後,定義另一個實作Comparator介面的類別'Comp',在其中使用'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);
       }
    }
    

    Output

    的中文翻译为:

    输出

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

    结论

    在本文中,我们首先定义了TreeMap类,然后介绍了TreeMap中的ClassCastException。在下一部分中,我们讨论了可以帮助解决这个ClassCastException的Comparator和Comparable接口。然后,我们看到了三个示例程序,展示了ClassCastException以及如何修复这个异常。

以上是使用Java中的TreeMap時如何解決java.lang.ClassCastException問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除