您的位置:首页 > 编程语言 > Java开发

java comparable 和 comparator 排序

2010-11-01 11:06 375 查看


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

Comparable是一个对象本身就已经支持自比较所需要实现的接口(如String Integer自己就可以完成比较大小操作)

而Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较。
comparable是通用的接口,用户可以实现它来完成自己特定的比较,而comparator可以看成一种算法的实现,在需要容器集合collection需要比较功能的时候,来指定这个比较器,这可以看出一种设计模式
comparable应该比较固定,和一个具体类相绑定,而comparator比较灵活,它可以被用于各个需要比较功能的类使用。可以说前者属于“静态绑定”,而后者可以“动态绑定”。
  一个类实现了Camparable接口表明这个类的对象之间是可以相互比较的。如果用数学语言描述的话就是这个类的对象组成的集合中存在一个全序。这样,这个类对象组成的集合就可以使用Sort方法排序了。
  而Comparator的作用有两个:
  1. 如果类的设计师没有考虑到Compare的问题而没有实现Comparable接口,可以通过 Comparator来实现比较算法进行排序
  2. 为了使用不同的排序标准做准备,比如:升序、降序或其他什么序
用法:
实现comparable类的实例就是可以排序的,重写compareTo(),只要调用sort(Object[] a)方法就可以,如果没有实现comparable接口,却调用sort(Object[] a)方法就会报错,因为sort()里面用到的mergeSort()方法将a转化成Comparable类型调用compareTo(T o)方法。
例子:
一。实现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

下面是要实现比较器

Java代码

public class Comparators {

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));

}

};

}

}

//测试

Java代码

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, Comparators.getComparator());

for (int i = 0; i < person.length; i++) {

System.out.println("after sort=" + person[i]);

}

}

}

另一个从网上摘的例子:
1,comparator

Java代码

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]);

}

}

}

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());

}

}

}

Java代码

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());

}

}

}

http://hi.baidu.com/kinny/blog/item/4b3eba7e93c453380cd7da16.html 摘的一段:
1.对象本身实现Comparable接口,那么该类的实例就是可以排序的.
有关Comparable: http://blog.csdn.net/treeroot/archive/2004/09/09/99613.aspx 只要实现了Comparable接口,就可以调用Collections的sort方法对集合中的元素排序.

2.指定一个Comparator,也就是实现了Comparator的类的一个实例.
但是Java本身只提供了一个Comparator的实现,就是Collections.reverseOrder().
该方法返回的是一个已经实现了Comparable接口的反序.

看一下Comparator的全部内容:

public interface Comparator {
  int compare(Object o1, Object o2);
  boolean equals(Object obj);
}
定义了两个方法,其实我们一般都只需要实现compare方法就行了,因为类都是默认从Object继承
所以会使用Object的equals方法.
Comparator一般都作为一个匿名类出现,对于没有实现Comparable的对象的集合,排序的时候
需要指定一个Comparator.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: