回复的代码行数好像有限制,补全:
- public static void method2() {
-
- //元素存入TreeSet时,会先进行比较,其元素是有指定顺序的。
- //我们这里在构造时指定比较器
- //观察下面3个比较器,比较的功能是重复的,用父类比较器即可。
- //也即可以写成:TreeSet<Person> ts1 = new TreeSet<Person>(new PersonCompImpl());
- //TreeSet<Student> ts2 = new TreeSet<Student>(new PersonCompImpl()());
- //TreeSet<Worker> ts3 = new TreeSet<Worker>(new PersonCompImpl()());
- TreeSet<Person> ts1 = new TreeSet<Person>(new PersonCompImpl());
- ts1.add(new Person());
- ts1.add(new Person());
- //创建存储Student类型元素的集合,并指定比较器
- TreeSet<Student> ts2 = new TreeSet<Student>(new StudentCompImpl());
- ts2.add(new Student());
- ts2.add(new Student());
- //创建存储Person类型元素的集合,并指定比较器
- TreeSet<Worker> ts3 = new TreeSet<Worker>(new WorkerCompImpl());
- ts3.add(new Worker());
- ts3.add(new Worker());
-
- }
- }
- class Person{
- //省略name,age属性,set,get方法
- }
- }
- class Student extends Person{}
- class Worker extends Person{}
- class PersonCompImpl implements Comparator<Person>{
- @Override
- public int compare(Person arg0, Person arg1) {
- //这里会调用arg0,arg1的getName(),getAge()方法进行比较
- return 0;
- }
- }
- class StudentCompImpl implements Comparator<Student>{
- @Override
- public int compare(Student arg0, Student arg1) {
- //这里也会调用arg0,arg1的getName(),getAge()方法进行比较
- return 0;
- }
- }
- class WorkerCompImpl implements Comparator<Worker>{
- @Override
- public int compare(Worker arg0, Worker arg1){
- //这里也会调用arg0,arg1的getName(),getAge()方法进行比较
- return 0;
- }
- }
复制代码 |