java中TreeSet或者TreeMap实现自定义对象的排序
TreeSet和TreeMap底层都是以二叉树为数据结构,TreeSet在存放引用类型的数据或者TreeMap以引用类型为键值时,需要让需要排序的对象所处的类实现Comparable接口 或者在构造这两个的集合的时候使用带比较器的构造方法。
// 定义学生类,实现Comparable接口
// 并复写compareTo方法,使学生具有比较这个行为
class Student implements Comparable<Student> {
int id;// 学生id
String name;// 学生姓名
int cScore;// 语文成绩
int mScore;// 数学成绩
int eScore;// 英语成绩
// 构造方法
public Student(int id, String name, int cScore, int mScore, int eScore) {
this.id = id;
this.name = name;
this.cScore = cScore;
this.mScore = mScore;
this