【java】实现Interface java.lang.Comparable接口的int compareTo(T o)方法实现对象数组或链表或集合的排序,和挽救式对象比较器Interface java.util.Comparator

时间:2022-04-21 10:55:55
 package 对象比较排序;

 import java.util.Arrays;

 class A implements Comparable<A>{
private String name;
private int age;
public A(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int compareTo(A o) {//此方法无需手工调用,Arrays会自动调用
if(this.age<o.age)
return -1;//1.this小于返回负数,this大于返回正数,则升序;
if(this.age>o.age)
return 1;//2.this小于返回正数,this大于返回负数,则降序;
return 0;//相等返回0
}
@Override
public String toString() {
return "name="+name+",age="+age+"\n";
}
}
public class TestComparable {
public static void main(String[] args) {
A[] as=new A[]{
new A("张三",63),
new A("李四",33),
new A("王五",53),
new A("赵六",43),
};
Arrays.sort(as);
System.out.println(Arrays.toString(as));
}
}

运行结果:

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


 package 对象比较排序;

 import java.util.Arrays;
import java.util.Comparator; class B{
private String name;
private int age;
public B(String name,int age){
this.name=name;
this.age=age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "name="+name+",age="+age+"\n";
}
}
class BComparator implements Comparator<B>{
@Override
public int compare(B o1, B o2) {
if(o1.getAge()<o2.getAge())
return -1;
if(o1.getAge()>o2.getAge())
return 1;
return 0;
}
}
public class TestComparator {
public static void main(String[] args) {
B[] bs=new B[]{new B("张三",44),
new B("李四",33),
new B("王二",55),
new B("赵六",66)};
BComparator bc=new BComparator();
Arrays.sort(bs, bc);
System.out.println(Arrays.toString(bs));
}
}

运行结果:

[name=李四,age=33
, name=张三,age=44
, name=王二,age=55
, name=赵六,age=66
]


如果需要对一组对象进行排序建议优先使用Comparable