Java中常見的比較子的實現方法

來源:互聯網
上載者:User

標籤:情況   out   一個   也會   private   compareto   基礎上   屬性   compare   

在Java中經常會涉及到對象數組的排序問題,那麼就涉及到對象之間的比較問題。


通常對象之間的比較可以從兩個方面去看:

第一個方面:對象的地址是否一樣,也就是是否引用自同一個對象。這種方式可以直接使用“==“來完成。

第二個方面:以對象的某一個屬性的角度去比較。


對於JDK8而言,有三種實現對象比較的方法:

1、覆寫Object類的equals()方法;

2、繼承Comparable介面,並實現compareTo()方法;

3、定義一個單獨的對象比較子,繼承自Comparator介面,實現compare()方法。

由於使用的排序方式的不同,具體選擇哪種方法來實現對象的比較也會有所不同。


第一種方法比較便於理解,複寫equals()方法一般用於自己實現的對象數組排序,而對於在應用Java內建的排序演算法時,使用後兩種方式都是可以實現的。

先來看一下第二種方式,這種方式就是讓自己編寫的類繼承Comparable介面,並實現介面的compareTo()方法,這種情況下,在使用java.util.Arrays.sort()方法時不用指定具體的比較子,sort()方法會使用對象自己的比較函數對對象進行排序。具體執行個體代碼如下:

  1 import java.util.Arrays;  2   3 class BookCook implements Comparable<BookCook>{  4 private String title;  5 private double price;  6 public BookCook(String title,double price){  7 this.title = title;  8 this.price = price;  9 } 10 @Override 11 public String toString() { 12 return "書名:"+this.title+",價格:"+this.price; 13 } 14 @Override 15 public int compareTo(BookCook o) { 16 if(this.price > o.price){ 17 return 1; 18 }else if(this.price < o.price){ 19 return -1; 20 }else{ 21 return 0; 22 } 23 } 24 }

從JDK1.8開始出現了Comparator介面,它的出現解決了當需要在已經開發好的代碼基礎上完善對象的比較功能時不想更改之前的代碼的問題。這種情況,我們需要單獨定義一個對象比較子,繼承Comparator介面。具體實現代碼如下:

  1 class Student {  2 private String name;  3 private double score;  4 public Student(String name,double score){  5 this.name = name;  6 this.score = score;  7 }  8 public double getScore(){  9 return this.score; 10 } 11 @Override 12 public String toString() { 13 return "姓名:"+this.name+",分數:"+this.score; 14 } 15  16 } 17 class StudentComparator implements Comparator<Student> { 18 @Override 19 public int compare(Student o1,Student o2) { 20 if(o1.getScore() > o2.getScore()){ 21 return 1; 22 }else if(o1.getScore() < o2.getScore()){ 23 return -1; 24 }else{ 25 return 0; 26 } 27 } 28 } 29 public class TestComparator { 30  31 public static void main(String[] args) { 32  33 Student[] sts = new Student[]{ 34 new Student("小戴",60), 35 new Student("小王",90), 36 new Student("老王",80), 37 new Student("小萱",95) 38 }; 39              40 java.util.Arrays.sort(sts, new StudentComparator()); 41 System.out.println(java.util.Arrays.toString(sts)); 42 } 43 }

以上三種情況,因具體情況的不同,選擇不同的方法解決實際的問題。

Java中常見的比較子的實現方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.