java comparator 与comparable_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java comparator 与comparable

java comparator 与comparable

 2018/6/9 18:20:32  zhangfortune  程序员俱乐部  我要评论(0)
  • 摘要:今天重新看了一下java的TreeSet,教程里面讲解了,对于自定义的class,当构造TreeSet的时候,需要传递一个Comparator,以防止ClassCastException。但是这样做的话,每个class需要一个实现comparator的比较类,比较繁琐。还有一种方法,自定义的class实现comparable接口。先上代码,最后说不同。1,实现comparatorclassTeacher{privateintage;Teacher(intage){this.age=age;
  • 标签:Java

今天重新看了一下java的TreeSet,教程里面讲解了,对于自定义class,当构造TreeSet的时候,需要传递一个Comparator,以防止ClassCastException。但是这样做的话,每个class需要一个实现comparator的比较类,比较繁琐。还有一种方法,自定义的class实现comparable接口。先上代码,最后说不同。

1,实现comparator

?

class Teacher {
    private int age;

    Teacher(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher:" + this.age;
    }
}

class TeacherComparator implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        Teacher t1 = (Teacher) o1;
        Teacher t2 = (Teacher) o2;
        return t1.getAge() - t2.getAge();
    }
}

//main method
TreeSet set2 = new TreeSet(new TeacherComparator());
set2.add(new Teacher(10));
set2.add(new Teacher(50));
set2.add(new Teacher(70));
set2.add(new Teacher(20));
set2.add(new Teacher(160));

System.out.println(set2);
//out put
[Teacher:10, Teacher:20, Teacher:50, Teacher:70, Teacher:160]

?上面为新增一个比较器class

?

2

class Student implements Comparable {
    private int score;

    Student(int score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student:" + this.score;
    }

    @Override
    public int compareTo(Object o) {
        Student s = (Student) o;
        return -(this.getScore() - s.getScore());
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

//main
TreeSet set = new TreeSet();
Student s1 = new Student(10);
Student s2 = new Student(30);
Student s3 = new Student(20);
Student s4 = new Student(70);
Student s5 = new Student(50);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
System.out.println(set);
//output
[Student:70, Student:50, Student:30, Student:20, Student:10]

实现了comparable接口。?

?

3.个人感觉实现comparable比较简单,实现起来不用新增一个class,不会那么繁琐。它们实现的接口不一样comparable实现comparaTo(Object o)接口,compartor实现compar(Object o1,Object o2)。

上一篇: Java程序员涨薪必备技能(1-5年必看!!!) 下一篇: 没有下一篇了!
发表评论
用户名: 匿名