A无参构造,按照默认自然排序,或者类实现Comparable中重写compareTo
B带参构造Comparator<? super T> Comparator, 通过匿名内部内进行比较器排序。
A :无参构造/自然排序—元素具备可比较性
让元素所属的类实现自然排序接口Comparable(默认排序),如有必要需在元素所属的类中重写compareTo,然后类中元素在添加进去的时候,自动调用该方法排序。
无参构造器,默认comparable排序或者在Student中override comparaTo();
TreeSet<Students> ts = new TreeSet<>();
class Student implements Comparable {
public int comparaTo( object o) {
//this是添加的实例对象,o是指定元素对象;
Student st = (Student) o;
}
}
B:比较器排序(集合具备比较性)
让集合的构造方法接受一个比较器接口的子类对象Comparator,类中元素按照接口方法排序。
带参构造,参数是接口Comparator的实现类对象,可以创建子类或者用匿名内部内
匿名内部内(可用Lambda简化)
TreeSet<Student> ts = new TreeSet<>(new Comparator(){
public int compara(E e1,E e2) {
//e1是添加元素,e2是根或者指定元素
}
});
实现类
TreeSet<Student> ts = new TreeSet<>(new MyComparator)
class MyComparator implements Comparator {
public int compara(E e1,E e2) {
}
}