首页 > 代码库 > Comparator

Comparator

Comparable接口和Comparator接口都是用来定义集合中的排序的,只是Comparable是在集合内部定义排序的实现,Comparator是在集合外部排序的实现。

Comparable 的在java.util中
Comparator 的在java.lang中

Comparable接口的实现表明这个类的对象之间是可以相互比较的,这个类对象组成的集合就可以直接使用sort方法排序。
Comparator可以看成一种算法的实现,将算法和数据分离,Comparator也可以在下面两种环境下使用:
1、类的设计师没有考虑到比较问题而没有实现Comparable,可以通过Comparator来实现排序而不必改变对象或类本身
2、对象之间可以使用多种排序方法

最好将equals方法也实现了,并且与compare方法对应。

 

一个例子:

-------------------------

package demos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

class Student {
    int age;
    String name;
    Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "[" + age + " , " + name + "]";
    }
}

class myComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.age != o2.age) {
            return o1.age - o2.age;
        }
        if (!o1.name.equals(o2.name)) {
            return o1.name.compareTo(o2.name);
        }
        return 0;
    }
}

class Teacher implements Comparable<Teacher> {
    private int age;
    private String name;
    Teacher(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public int compareTo(Teacher o) {
        if (age != o.age) {
            return age - o.age;
        }
        if (!name.equals(o.name)) {
            return name.compareTo(o.name);
        }
        return 0;
    }
    
    @Override
    public String toString() {
        return "[" + age + " , " + name + "]";
    }
}

public class ComparaTest {
    public static void main(String[] args) {
        Student s1 = new Student(10, "5li");
        Student s2 = new Student(10, "4wang");
        Student s3 = new Student(16, "3zh");
        Student s4 = new Student(16, "2omg");
        Student s5 = new Student(19, "1hehe");

        // 比较器是必须的,否则抛异常class cannot be cast to java.lang.Comparable
        Set set = new TreeSet(new myComparator());
        set.add(s5);
        set.add(s4);
        set.add(s3);
        set.add(s2);
        set.add(s1);
        System.out.println(set);

        Teacher t1 = new Teacher(10, "5li");
        Teacher t2 = new Teacher(10, "4wang");
        Teacher t3 = new Teacher(16, "3zh");
        Teacher t4 = new Teacher(16, "2omg");
        Teacher t5 = new Teacher(19, "1hehe");
        List l = new ArrayList();
        l.add(t5);
        l.add(t4);
        l.add(t3);
        l.add(t2);
        l.add(t1);
        Collections.sort(l);
        System.out.println(l);
    }
}

-------------------------

 

end

Comparator