代码:
class StudentTest implements Comparable<StudentTest> { private String name; private int age; public StudentTest() { } public StudentTest(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "name:" + this.name + ";age:" + this.age; } @Override public int compareTo(StudentTest o) { // 先按age排序 if (this.age > o.getAge()) { return (this.age - o.getAge()); } if (this.age < o.getAge()) { return (this.age - o.getAge()); } // 再按name排序 if (this.name.compareTo(o.getName()) > 0) { return 1; } if (this.name.compareTo(o.getName()) < 0) { return -1; } return 0; } }
使用:
StudentTest[] list = new StudentTest[4]; list[0] = new StudentTest("b1", 20); list[1] = new StudentTest("a2", 50); list[2] = new StudentTest("a1", 20); list[3] = new StudentTest("b2", 40); Arrays.sort(list); System.out.println(Arrays.toString(list));
输出:
[name:a1;age:20, name:b1;age:20, name:b2;age:40, name:a2;age:50]
说明:返回值大于0:靠前;等于0:不变;小于零:靠后。
Comparator方式:
Arrays.sort(list,new Comparator<StudentTest>() { @Override public int compare(StudentTest o1, StudentTest o2) { // 先按age倒序排序 if (o1.getAge() > o2.getAge()) { return -1; } if (o1.getAge() < o2.getAge()) { return 1; } // 再按name倒序 if (o1.getName().compareTo(o2.getName()) > 0) { return -1; } if (o1.getName().compareTo(o2.getName()) < 0) { return 1; } return 0; } }); System.out.println(Arrays.toString(list));
输出:[name:a2;age:50, name:b2;age:40, name:b1;age:20, name:a1;age:20]