Comparable和Comparator2个接口的作用和区别

Comparable和Comparator是JDK中定义的2个比较接口,很相似,但又有所不同。

这2个接口的作用和区别也是Java中的常见经典面试题。

下面我们就来详细介绍下这2个接口的定义、作用、区别、模式、应用场景和代码案例。

定义

  1. public interface Comparable<T> {  
  2.    public int compareTo(T o);  
  3. }  
  4. public interface Comparator<T> {  
  5.    int compare(T o1, T o2);  
  6.    boolean equals(Object obj);  
  7. }  
public interface Comparable<T> {
   public int compareTo(T o);
}
public interface Comparator<T> {
   int compare(T o1, T o2);
   boolean equals(Object obj);
}


作用

用来实现集合中元素的比较和排序。

区别

Comparable强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。

实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。

Comparator强行对某个对象 collection 进行整体排序 的比较函数。可以将 Comparator 传递给 sort 方法(如 Collections.sort 或 Arrays.sort),从而允许在排序顺序上实现精确控制。还可以使用 Comparator 来控制某些数据结构(如有序 set或有序映射)的顺序,或者为那些没有自然顺序的对象 collection 提供排序。

可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。

模式

用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。

Comparator可以看成一种算法的实现,将算法和数据分离。

应用场景

Comparator也可以在下面两种环境下使用:
1、类的设计师没有考虑到比较问题而没有实现Comparable,可以通过Comparator来实现排序而不必改变对象本身。
2、可以使用多种排序标准,比如员工按照员工号、年龄、名字 升序或降序排序等。

代码案例

  1. //员工   
  2. public class Employee implements Comparable<Employee> {  
  3.     // 员工号   
  4.     private int no;  
  5.     // 员工的年龄   
  6.     private int age;  
  7.     // 员工的姓名   
  8.     private String name;  
  9.   
  10.     public Employee() {  
  11.         super();  
  12.     }  
  13.   
  14.     public Employee(int no, int age, String name) {  
  15.         super();  
  16.         this.no = no;  
  17.         this.age = age;  
  18.         this.name = name;  
  19.     }  
  20.   
  21.     public int getNo() {  
  22.         return no;  
  23.     }  
  24.   
  25.     public void setNo(int no) {  
  26.         this.no = no;  
  27.     }  
  28.   
  29.     public int getAge() {  
  30.         return age;  
  31.     }  
  32.   
  33.     public void setAge(int age) {  
  34.         this.age = age;  
  35.     }  
  36.   
  37.     public String getName() {  
  38.         return name;  
  39.     }  
  40.   
  41.     public void setName(String name) {  
  42.         this.name = name;  
  43.     }  
  44.   
  45.     // 自然排序按照员工号的顺序   
  46.     public int compareTo(Employee obj) {  
  47.         Employee employee = (Employee) obj;  
  48.         return this.no - employee.no;  
  49.     }  
  50.   
  51.     @Override  
  52.     public String toString() {  
  53.         return "Employee [no=" + no + ", age=" + age + ", name=" + name + "]";  
  54.     }  
  55.   
  56.     @Override  
  57.     public int hashCode() {  
  58.         final int prime = 31;  
  59.         int result = 1;  
  60.         result = prime * result + no;  
  61.         return result;  
  62.     }  
  63.   
  64.     @Override  
  65.     public boolean equals(Object obj) {  
  66.         if (this == obj)  
  67.             return true;  
  68.         if (obj == null)  
  69.             return false;  
  70.         if (getClass() != obj.getClass())  
  71.             return false;  
  72.         Employee other = (Employee) obj;  
  73.         if (no != other.no)  
  74.             return false;  
  75.         return true;  
  76.     }  
  77.   
  78. }  
//员工
public class Employee implements Comparable<Employee> {
    // 员工号
    private int no;
    // 员工的年龄
    private int age;
    // 员工的姓名
    private String name;

    public Employee() {
        super();
    }

    public Employee(int no, int age, String name) {
        super();
        this.no = no;
        this.age = age;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // 自然排序按照员工号的顺序
    public int compareTo(Employee obj) {
        Employee employee = (Employee) obj;
        return this.no - employee.no;
    }

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

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + no;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (no != other.no)
            return false;
        return true;
    }

}


 

  1. /** 
  2.  * 
  3.  * 按照员工的年龄进行比较的比较器。 
  4.  */  
  5. public class AgeComparator implements Comparator<Employee> {  
  6.   
  7.     @Override  
  8.     public int compare(Employee o1, Employee o2) {  
  9.         return o1.getAge()-o2.getAge();  
  10.     }  
  11.   
  12. }  
/**
 *
 * 按照员工的年龄进行比较的比较器。
 */
public class AgeComparator implements Comparator<Employee> {

    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getAge()-o2.getAge();
    }

}


 

  1. /** 
  2.  * 
  3.  *按照员工的名字进行比较的比较器 
  4.  * 
  5.  */  
  6. public class NameComparator implements Comparator<Employee> {  
  7.   
  8.     @Override  
  9.     public int compare(Employee o1, Employee o2) {  
  10.         return o1.getName().compareTo(o2.getName());  
  11.     }  
  12.   
  13. }  
/**
 *
 *按照员工的名字进行比较的比较器
 *
 */
public class NameComparator implements Comparator<Employee> {

    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getName().compareTo(o2.getName());
    }

}


 

  1. public class EmployeeTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Employee employee1 = new Employee(16924"LeiWen");  
  5.         Employee employee2 = new Employee(15227"FansUnion");  
  6.   
  7.         List<Employee> employeeList = new ArrayList<Employee>();  
  8.         employeeList.add(employee1);  
  9.         employeeList.add(employee2);  
  10.   
  11.         // 原始排序   
  12.         println("原始排序");  
  13.         println(employeeList);  
  14.           
  15.         // 自然排序,默认排序   
  16.         println("默认no升序排序");  
  17.         Collections.sort(employeeList);  
  18.         println(employeeList);  
  19.           
  20.         // 按名字排序   
  21.         println("自定义name升序排序");  
  22.         Collections.sort(employeeList,new NameComparator());  
  23.         println(employeeList);  
  24.           
  25.           
  26.         // 按年龄排序   
  27.         println("自定义age升序排序");  
  28.         Collections.sort(employeeList,new AgeComparator());  
  29.         println(employeeList);  
  30.     }  
  31.   
  32.     private static void println(String str){  
  33.         System.out.println(str);  
  34.     }  
  35.     private static void println(List<Employee> employeeList) {  
  36.         System.out.println(employeeList);  
  37.     }  
  38. }  
public class EmployeeTest {

    public static void main(String[] args) {
        Employee employee1 = new Employee(169, 24, "LeiWen");
        Employee employee2 = new Employee(152, 27, "FansUnion");

        List<Employee> employeeList = new ArrayList<Employee>();
        employeeList.add(employee1);
        employeeList.add(employee2);

        // 原始排序
        println("原始排序");
        println(employeeList);
        
        // 自然排序,默认排序
        println("默认no升序排序");
        Collections.sort(employeeList);
        println(employeeList);
        
        // 按名字排序
        println("自定义name升序排序");
        Collections.sort(employeeList,new NameComparator());
        println(employeeList);
        
        
        // 按年龄排序
        println("自定义age升序排序");
        Collections.sort(employeeList,new AgeComparator());
        println(employeeList);
    }

    private static void println(String str){
        System.out.println(str);
    }
    private static void println(List<Employee> employeeList) {
        System.out.println(employeeList);
    }
}


运行结果

原始排序
[Employee [no=169, age=24, name=LeiWen], Employee [no=152, age=27, name=FansUnion]]
默认no升序排序
[Employee [no=152, age=27, name=FansUnion], Employee [no=169, age=24, name=LeiWen]]
自定义name升序排序
[Employee [no=152, age=27, name=FansUnion], Employee [no=169, age=24, name=LeiWen]]
自定义age升序排序
[Employee [no=169, age=24, name=LeiWen], Employee [no=152, age=27, name=FansUnion]]


参考资料

http://www.iteye.com/problems/3025

http://ctzlylc.blog.163.com/blog/static/61967136201165981283/

JDK API中文参考手册

OpenJDK源码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值