在Java中透過實現Comparable介面排序自定義物件


Java 提供了各種排序演算法和方法,可以幫助我們排序陣列、列表或任何集合。Comparable 介面是一種額外的方法,當我們想要按其自然順序排序自定義物件時非常有用。例如,它按字典順序排序字串,按數字順序排序數字。此介面位於 'java.lang' 包中。

在這篇文章中,我們將透過示例學習 Comparable 介面的使用。此外,我們還將討論 Collection 介面的一些方法和類,這些方法和類將幫助我們使用 Comparable 介面對自定義物件進行排序。

透過實現 Comparable 介面進行排序

Comparable 介面的語法

class nameOfclass implements Comparable<nameOfclass>

在進入程式之前,讓我們瞭解一些類和方法。

compareTo() 方法

Comparable 介面只定義了一個名為 'compareTo' 的方法,可以重寫該方法以對物件的集合進行排序。它賦予了比較一個類的物件自身的能力。當“this”物件等於傳入的物件時返回 0,如果“this”物件大於傳入的物件則返回正值,否則返回負值。

語法

compareTo( nameOfclass nameOfobject ); 

Collections.sort() 方法

Collection 介面的 'Collections' 類提供了一個名為 'Collections.sort()' 的靜態方法,該方法可以對指定集合(如 ArrayList 或 LinkedList)的元素進行排序。它位於 'java.util' 包中。

語法

Collections.sort( nameOfcollection );

演算法

  • 步驟 1 − 我們將從匯入 'java.util' 包開始,以便在程式中使用 'sort()' 方法。

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

  • 步驟 3 − 接下來,我們將使用 'toString()' 方法將物件的資料轉換為字串。然後,定義 'compareTo' 方法以及一個作為引數的 'Cart' 類物件,以將 'this' 物件與新建立的物件進行比較。

  • 步驟 4 − 現在,在 main() 方法中,宣告一個名為 'obj' 的集合型別 ArrayList 的 'Cart' 類物件,並使用名為 'add()' 的內建方法將物件詳細資訊儲存到集合中。

  • 步驟 5 − 最後,我們將 'obj' 作為引數傳遞給 'Collections.sort()' 方法以執行排序操作,並使用 for each 迴圈列印結果。

示例

import java.util.*;
public class Cart implements Comparable<Cart> {
   String item;
   double price;
   Cart(String item, int price) {
      // this keyword shows these variables belongs to constructor
      this.item = item; 
      this.price = price;
   }
   // method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   // overriding method
   public int compareTo(Cart comp) {
      if(this.price > comp.price) {
         return 1;
      } else {
         return -1;
      }
   }
   public static void main(String[] args) {
      // Declaring collection arraylist
      List<Cart> obj = new ArrayList<>();
      // Adding object to the collection
      obj.add(new Cart("Rice", 59));
      obj.add(new Cart("Milk", 60));
      obj.add(new Cart("Bread", 45));
      obj.add(new Cart("Peanut", 230));
      obj.add(new Cart("Butter", 55));
      System.out.println("The original Objects: ");
      // to print unsorted list of objects
      for(Cart print : obj) {
         System.out.println(print);	
      }
      Collections.sort(obj); 
      // Sorting the object
      System.out.println("The newly sorted Objects: ");
      // to print newly sorted list of objects
      for(Cart print : obj) {
         System.out.println(print);	
      }
   }
}

輸出

The original Objects: 
Item: Rice, Price: 59.0
Item: Milk, Price: 60.0
Item: Bread, Price: 45.0
Item: Peanut, Price: 230.0
Item: Butter, Price: 55.0
The newly sorted Objects: 
Item: Bread, Price: 45.0
Item: Butter, Price: 55.0
Item: Rice, Price: 59.0
Item: Milk, Price: 60.0
Item: Peanut, Price: 230.0

結論

在 Java 1.0 版本中,Comparable 介面首次引入並可在 'java.lang' 包中使用。通常,在此包中定義的類、方法和介面預設情況下可用,因此在使用前無需匯入。本文解釋了 Comparable 介面的實現,並且我們還了解了其內建方法 'compareTo()' 的用法。

更新於:2023年5月12日

584 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告