使用 arrays.sort() 配合自定义 comparator 即可实现排序。在比较器中通过 instanceof 判断对象类型,或统一调用父类方法获取排序依据字段,从而对包含不同子类的父类引用数组进行稳定排序。

按子类类型优先级排序
当需要根据对象的实际子类类型(如先排 Student 后排 Teacher)进行排序时,可以在 Comparator 中使用 instanceof 检查并赋予不同的权重值。

import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Teacher("Alice");
people[1] = new Student("Bob");
people[2] = new Student("Charlie");
Arrays.sort(people, new Comparator<person>() {
@Override
public int compare(Person p1, Person p2) {
boolean isS1 = p1 instanceof Student;
boolean isS2 = p2 instanceof Student;
if (isS1 && !isS2) return -1;
if (!isS1 && isS2) return 1;
return p1.getName().compareTo(p2.getName());
}
});
for (Person p : people) {
System.out.println(p.getClass().getSimpleName() + ": " + p.getName());
}
}
}
class Person { private String name; public Person(String n) { name = n; } public String getName() { return name; } }
class Student extends Person { public Student(String n) { super(n); } }
class Teacher extends Person { public Teacher(String n) { super(n); } }</person>
运行结果:
Student: Bob
Student: Charlie
Teacher: Alice
按子类特定属性排序
如果不同子类拥有共同的排序逻辑(例如都实现了 getScore()),则无需区分类型,直接调用多态方法进行比较即可。

import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Teacher("Alice", 90);
people[1] = new Student("Bob", 85);
people[2] = new Student("Charlie", 95);
Arrays.sort(people, Comparator.comparingInt(Person::getScore));
for (Person p : people) {
System.out.println(p.getClass().getSimpleName() + ": " + p.getScore());
}
}
}
class Person { protected int score; public int getScore() { return score; } }
class Student extends Person { public Student(String n, int s) { score = s; } }
class Teacher extends Person { public Teacher(String n, int s) { score = s; } }
运行结果:
Student: 85
Teacher: 90
Student: 95
处理未实现方法的子类
若某些子类未实现通用接口方法,需在比较器中增加空值或类型检查以防止 ClassCastException 或 NullPointerException。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











