既然看到了Comparable和Comparator了,那你应该也看过了多线程。
多线程的extends Thread 和 implements Runnable 和这个感觉有点类似的意思。
Comparable是让类实现该接口,具有比较性,但是,如果想用另一种比较方式,需要修改代码,这不合适。
所以就有了Comparator,实现Comparator接口,实现compare方法,定义自己的比较方法,如果需要用这种比较方式,就吧该类穿进去,让代码更加灵活
这也体现了接口的好处,扩展性更强
如下面代码:
- import java.util.*;
- class TreeSetDemo2{
- public static void main(String[]args){
- TreeSet ts=new TreeSet(new MyCompare());
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi07",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi01",40));
- for(Iterator<Student> iter=ts.iterator();iter.hasNext();){
- Student stu=(Student)iter.next();
- System.out.println(stu.getName()+"..."+stu.getAge());
- }
- }
- }
- class Student implements Comparable{
- private String name;
- private int age;
-
- Student(String name, int age){
- this.name=name;
- this.age=age;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- @Override
- public int compareTo(Object o) {
- if(!(o instanceof Student))
- throw new RuntimeException("传值类型不是学生");
- Student s=(Student)o;
- if(this.age>s.age){
- return 1;
- }
- if(this.age==s.age){
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- }
- class MyCompare implements Comparator{
- public int compare(Object o1,Object o2){
- Student s1=(Student)o1;
- Student s2=(Student)o2;
- int result=s1.getName().compareTo(s2.getName());
- if(result==0){
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- }
- return result;
- }
- }
复制代码 |