首页 > 代码库 > 【java】实现Interface Comparable<T>接口的int compareTo(T o)方法实现对象数组或链表或集合的排序

【java】实现Interface Comparable<T>接口的int compareTo(T o)方法实现对象数组或链表或集合的排序

技术分享
 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     @Override
13     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;//相等返回0
19     }
20     @Override
21     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)方法实现对象数组或链表或集合的排序