【java】實現Interface Comparable<T>介面的int compareTo(T o)方法實現對象數組或鏈表或集合的排序

來源:互聯網
上載者:User

標籤:排序   display   相等   opened   print   package   system   color   技術   

 1 package 對象比較排序; 2  3 import java.util.Arrays; 4  5 class A implements Comparable<A>{ 6     private String name; 7     private int age; 8     public A(String name,int age){ 9         this.name=name;10         this.age=age;11     }12     @Override13     public int compareTo(A o) {//此方法無需手工調用,Arrays會自動調用14         if(this.age<o.age)15             return -1;//1.this小於返回負數,this大於返回正數,則升序;16         if(this.age>o.age)17             return 1;//2.this小於返回正數,this大於返回負數,則降序;18         return 0;//相等返回019     }20     @Override21     public String toString() {22         return "name="+name+",age="+age+"\n";23     }24 }25 public class TestComparable {26     public static void main(String[] args) {27         A[] as=new A[]{28                     new A("張三",63),29                     new A("李四",33),30                     new A("王五",53),31                     new A("趙六",43),32                 };33         Arrays.sort(as);34         System.out.println(Arrays.toString(as));35     }36 }
View Code

運行結果:

[name=李四,age=33
, name=趙六,age=43
, name=王五,age=53
, name=張三,age=63
]

【java】實現Interface Comparable<T>介面的int compareTo(T o)方法實現對象數組或鏈表或集合的排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.