自定义比较器实现
import java.util.Comparator;
class Student {
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public int getAge() {
return age;
}
public int getScore() {
return score;
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.getAge() != s2.getAge()) {
return s1.getAge() - s2.getAge();
} else {
return s2.getScore() - s1.getScore();
}
}
}
在TreeMap中使用该比较器的注意事项
- 唯一性:TreeMap基于红黑树实现,要求键对象必须是唯一的。当使用自定义对象作为键时,依据比较器的逻辑,若两个对象比较结果为0,TreeMap会认为它们是相同的键,后插入的对象会覆盖先插入的对象。
- 非空性:TreeMap的键不能为null。若尝试插入null键,会抛出
NullPointerException
。所以在使用自定义对象作为键时,要确保对象不会为null。
- 一致性:比较器的实现逻辑应保持一致。即对于任意的
a
、b
和c
,如果compare(a, b) == 0
且compare(b, c) == 0
,那么compare(a, c) == 0
;如果compare(a, b) < 0
且compare(b, c) < 0
,那么compare(a, c) < 0
。否则在TreeMap的一些操作(如查找、删除等)中可能会出现意外结果。