1. 实现comparable接口
    2. 重写compareTo接口 接口中定义排序规则 ```java

    /**

    • @author:LYY 创建时间:2022/5/3 */ public class ComparableTest {

      public static void main(String[] args) {

      1. Person[] arr = new Person[4];
      2. arr[0] = new Person(19, "张三", "朝阳大街");
      3. arr[1] = new Person(17, "李四", "饭都花园");
      4. arr[2] = new Person(88, "唐人", "唐人街");
      5. arr[3] = new Person(99, "王五", "天堂办事处");
      6. Arrays.sort(arr);
      7. System.out.println(Arrays.toString(arr));

      } }

    class Person implements Comparable{

    1. private int age;
    2. private String name;
    3. private String address;
    4. public Person(int age, String name, String address) {
    5. this.age = age;
    6. this.name = name;
    7. this.address = address;
    8. }
    9. public int getAge() {
    10. return age;
    11. }
    12. public void setAge(int age) {
    13. this.age = age;
    14. }
    15. public String getName() {
    16. return name;
    17. }
    18. public void setName(String name) {
    19. this.name = name;
    20. }
    21. public String getAddress() {
    22. return address;
    23. }
    24. public void setAddress(String address) {
    25. this.address = address;
    26. }
    27. @Override
    28. public String toString() {
    29. return "Person{" +
    30. "age=" + age +
    31. ", name='" + name + '\'' +
    32. ", address='" + address + '\'' +
    33. '}';
    34. }
    35. /**
    36. * 根据person对象的age属性进行比较
    37. * @param o
    38. * @return
    39. */
    40. @Override
    41. public int compareTo(Object o) {
    42. // 判断形参是否是Person类
    43. if (o instanceof Person) {
    44. Person p = (Person) o;
    45. // 当前对象大于形参 返回正整数
    46. if (this.age > p.getAge()) {
    47. return 1;
    48. } else if (this.age < p.getAge()) {
    49. return -1;
    50. } else {
    51. return 0;
    52. }
    53. }
    54. throw new RuntimeException("参数类型不正确!");
    55. }

    } ```