实现该接口的类可以对该类的数组进行排序Arrays.sort(list)。也可以对该类的集合进行排序list.sort(null)。
package com.andy.springtransaction.alibaba; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { //数组 Student[] stu = {new Student(1,"1"),new Student(3,"3"),new Student(2,"2")}; Arrays.sort(stu); for (Student ss : stu){ System.out.println(ss); } System.out.println("-------我是分割线-------"); //集合 List<Student> list = new ArrayList<>(); list.add(new Student(1,"1")); list.add(new Student(3,"3")); list.add(new Student(2,"2")); list.sort(null); // 或 Collections.sort(list); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } //需要进行比较的实体,实现 Comparable 接口 class Student implements Comparable<Student>{ public Student(){ } public Student(Integer id,String name){ this.id=id; this.name=name; } private Integer id; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public int compareTo(Student o) { return this.getId() - o.getId(); } }