- 实现comparable接口
- 重写compareTo接口 接口中定义排序规则 ```java
/**
@author:LYY 创建时间:2022/5/3 */ public class ComparableTest {
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(19, "张三", "朝阳大街");
arr[1] = new Person(17, "李四", "饭都花园");
arr[2] = new Person(88, "唐人", "唐人街");
arr[3] = new Person(99, "王五", "天堂办事处");
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
} }
class Person implements Comparable{
private int age;
private String name;
private String address;
public Person(int age, String name, String address) {
this.age = age;
this.name = name;
this.address = address;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
/**
* 根据person对象的age属性进行比较
* @param o
* @return
*/
@Override
public int compareTo(Object o) {
// 判断形参是否是Person类
if (o instanceof Person) {
Person p = (Person) o;
// 当前对象大于形参 返回正整数
if (this.age > p.getAge()) {
return 1;
} else if (this.age < p.getAge()) {
return -1;
} else {
return 0;
}
}
throw new RuntimeException("参数类型不正确!");
}
} ```