---
title: "15.JAVA中的Comparator和Comparable"
author: "zzhblh"
date: "2012-04-05T11:50:13Z"
tags: []
slug: "15-java-comparator-comparable"
draft: false
lastmod: "2012-05-23T12:49:59Z"
id: 1474292
url: "https://zzhblh.iteye.com/blog/1474292"
---

Comparable和Comparator区别

comparable是通用的接口，用户可以实现它来完成自己特定的比较，而comparator可以看成一种算法的实现，在需要容器集合collection需要比较功能的时候，来指定这个比较器。

comparable应该比较固定，和一个具体类相绑定，而comparator比较灵活，它可以被用于各个需要比较功能的类使用。可以说前者属于“静态绑定”，而后者可以“动态绑定”。
 　　一个类实现了Camparable接口表明这个类的对象之间是可以相互比较的。如果用数学语言描述的话就是这个类的对象组成的集合中存在一个全序。这样，这个类对象组成的集合就可以使用Sort方法排序了。
而Comparator的作用有两个： 
1. 如果类的设计师没有考虑到Compare的问题而没有实现Comparable接口，可以通过　Comparator来实现比较算法进行排序 
2. 为了使用不同的排序标准做准备，比如：升序、降序或其他什么序 

一.实现comparable接口 


```java
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接口 


```java
public class Person {
String firstname,lastname;
Boolean sex;
Integer age;
public Person(String firstname,String lastname,Boolean sex,Integer age) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.sex = sex;
    this.age = age;
}
public String getFirstName() {
     return firstname;
   } 
   public String getLastName() {
     return lastname;
   }
   public Boolean getSex() {
      return sex;
    }
 
    public Integer getAge() {
      return age;
    }

//为了输入方便，重写了toString()
 
public String toString()
    {
      return firstname +" "+lastname+" "+(sex.booleanValue()?"男":"女")+" "+age;
    }
}
//end person

下面是要实现比较器


public class MyComparator{
public static java.util.Comparator getComparator() {
    return new java.util.Comparator() {
 
      public int compare(Object o1, Object o2) {
        if (o1 instanceof String) {
          return compare( (String) o1, (String) o2);
        }
       else if (o1 instanceof Integer) {
          return compare( (Integer) o1, (Integer) o2);
        }
 
       else if (o1 instanceof Person) {
      return compare( (Person) o1, (Person) o2);
    }
 
        else {
          System.err.println("未找到合适的比较器");
          return 1;
 
        }
      }
 
      public int compare(String o1, String o2) {
        String s1 = (String) o1;
        String s2 = (String) o2;
        int len1 = s1.length();
        int len2 = s2.length();
        int n = Math.min(len1, len2);
        char v1[] = s1.toCharArray();
        char v2[] = s2.toCharArray();
        int pos = 0;
 
        while (n-- != 0) {
          char c1 = v1[pos];
          char c2 = v2[pos];
          if (c1 != c2) {
            return c1 - c2;
          }
          pos++;
        }
        return len1 - len2;
      }
 
      public int compare(Integer o1, Integer o2) {
        int val1 = o1.intValue();
        int val2 = o2.intValue();
        return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));
 
      }
      public int compare(Boolean o1, Boolean o2) {
 
         return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1));
 
       }
 
      public int compare(Person o1, Person o2) {
        String firstname1 = o1.getFirstName();
        String firstname2 = o2.getFirstName();
        String lastname1 = o1.getLastName();
        String lastname2 = o2.getLastName();
        Boolean sex1 = o1.getSex();
        Boolean sex2 = o2.getSex();
        Integer age1 = o1.getAge();
        Integer age2 = o2.getAge();
        return (compare(firstname1, firstname2) == 0 ?
                (compare(lastname1, lastname2) == 0 ? (compare(sex1, sex2) == 0 ? (compare(age1, age2) == 0 ? 0 :
                 compare(age1, age2)) :
                 compare(sex1, sex2)) :
                 compare(lastname1, lastname2)) :
                compare(firstname1, firstname2));
 
      }
 
    };
}
 
}
//测试
 
public class Main {
public Main() {
}
public static void main(String[] args) {
    Person[] person = new Person[] {
         new Person("ouyang", "feng", Boolean.TRUE, new Integer(27)),
         new Person("zhuang", "gw", Boolean.TRUE, new Integer(27)),
         new Person("zhuang", "gw", Boolean.FALSE, new Integer(27)),
         new text.Person("zhuang", "gw", Boolean.FALSE, new Integer(2))
     };
     for (int i = 0; i < person.length; i++) {
       System.out.println("before sort=" + person[i]);
     }
     java.util.Arrays.sort(person, MyComparator.getComparator());
    for (int i = 0; i < person.length; i++) {
      System.out.println("after sort=" + person[i]);
    }
 
}
 
}










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]);
    }
  }

}



```