---
title: "Comparable Comparator 的区别"
author: "chenzehe"
date: "2013-09-03T14:34:13Z"
tags: []
categories: ["编程语言"]
slug: "comparable-comparator"
draft: false
lastmod: "2013-09-03T14:33:45Z"
id: 1935896
url: "https://chenzehe.iteye.com/blog/1935896"
---

注：本文为转载

当需要排序的集合或数组不是单纯的数字型时，通常可以使用Comparator或Comparable，以简单的方式实现对象排序或自定义排序。

**一、Comparator**

```
public interface Comparator<T> {
    /** 
    * @return o1小于、等于或大于o2，分别返回负整数、零或正整数。 
    */ 
    int compare(T o1, T o2);
    boolean equals(Object obj);
}
```

强行对某个对象collection进行整体排序的比较函数，可以将Comparator传递给Collections.sort或Arrays.sort。 如：

```
import java.util.Arrays;
import java.util.Comparator;

public class SampleComparator implements Comparator {

  public int compare(Object o1, Object o2) {
    return toInt(o1) - toInt(o2);
  }

  private int toInt(Object o) {
    String str = (String) o;
    str = str.replaceAll("一", "1");
    str = str.replaceAll("二", "2");
    str = str.replaceAll("三", "3");
    // 
    return Integer.parseInt(str);
  }

  /**
   * 测试方法
   */
  public static void main(String[] args) {
    String[] array = new String[] { "一二", "三", "二" };
    Arrays.sort(array, new SampleComparator());
    for (int i = 0; i < array.length; i++) {
      System.out.println(array[i]);
    }
  }

}
```

 

**二、Comparable**

```
public interface Comparable<T> {
    public int compareTo(T o);
}
```

强行对实现它的每个类的对象进行整体排序，实现此接口的对象列表（和数组）可以通过Collections.sort或Arrays.sort进行自动排序。如假设对象User，需要按年龄排序：

```
public class User {

  private String id;
  private int age;

  public User(String id, int age) {
    this.id = id;
    this.age = age;
  }

  public int getAge() {
    return age;
  }

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

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

}
```

使用Comparable改后为：

```
import java.util.Arrays;

public class User implements Comparable {

  private String id;
  private int age;

  public User(String id, int age) {
    this.id = id;
    this.age = age;
  }

  public int getAge() {
    return age;
  }

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

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public int compareTo(Object o) {
    return this.age - ((User) o).getAge();
  }

  /**
   * 测试方法
   */
  public static void main(String[] args) {
    User[] users = new User[] { new User("a", 30), new User("b", 20) };
    Arrays.sort(users);
    for (int i = 0; i < users.length; i++) {
      User user = users[i];
      System.out.println(user.getId() + " " + user.getAge());
    }
  }

}
```

 

**三、Comparator和Comparable的区别**

先看一下使用Comparator对User集合实现排序的方式：

```
import java.util.Arrays;
import java.util.Comparator;

public class UserComparator implements Comparator {

  public int compare(Object o1, Object o2) {
    return ((User) o1).getAge() - ((User) o2).getAge();
  }

  /**
   * 测试方法
   */
  public static void main(String[] args) {
    User[] users = new User[] { new User("a", 30), new User("b", 20) };
    Arrays.sort(users, new UserComparator());
    for (int i = 0; i < users.length; i++) {
      User user = users[i];
      System.out.println(user.getId() + " " + user.getAge());
    }
  }

}
```

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