Comparable接口:
概念:此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
- 为什么要使用这个类?
我们都知道Arrays包下有sort方法是进行排序的,可是底层是怎样实现的,其实他也是实现了Comparable接口。里面实现了compareTo方法,所以按照某种规则能够排序。 - 那问题有来了如果数组类型是自定义的类型那怎么排序?
对呀,只能让我们自己实现Comparable接口同时实现compareTo方法,让按照我们的想法进行排序。
public class Person implements Comparable<Person>{
private int age;
private String name;
private int high;
public Person() {
}
public Person(int age, String name, int high) {
this.age = age;
this.name = name;
this.high = high;
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setHigh(int high) {
this.high = high;
}
public int getHigh() {
return high;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
", high=" + high +
'}';
}
@Override
public int compareTo(Person o) {
// return this.getAge() - o.getAge(); //年龄升序
return o.getAge() - this.getAge(); //年龄降序
// return this.getHigh() - o.getHigh(); //身高升序
}
}
import java.util.Arrays;
public class TestPerson {
public static void main(String[] args) {
Person[] list = new Person[]{
new Person(20,"MAHANG",180),
new Person(22,"jinp",170),
new Person(24,"SS",90)
};
Arrays.sort(list);
for(Person x:list){
System.out.println(x.toString());
}
}
}