原文:http://blog.csdn.net/u012289441/article/details/45154401?ref=myread
1. Comparator 和 Comparable 相同的地方
他们都是java的一个接口, 并且是用来对自定义的class比较大小的,
什么是自定义class: 如 public class Person{ String name; int age }.
当我们有这么一个personList,里面包含了person1, person2, persion3....., 我们用Collections.sort( personList ),
是得不到预期的结果的. 这时肯定有人要问, 那为什么可以排序一个字符串list呢:
如 StringList{"hello1" , "hello3" , "hello2"}, Collections.sort( stringList ) 能够得到正确的排序, 那是因为
String 这个对象已经帮我们实现了 Comparable接口 , 所以我们的 Person 如果想排序, 也要实现一个比较器。
2. Comparator 和 Comparable 的区别
Comparable
Comparable 定义在 Person类的内部:
public class Persion implements Comparable {..比较Person的大小..},
因为已经实现了比较器,那么我们的Person现在是一个可以比较大小的对象了,它的比较功能和String完全一样,可以随时随地的拿来
比较大小,因为Person现在自身就是有大小之分的。Collections.sort(personList)可以得到正确的结果。
Comparator
Comparator 是定义在Person的外部的, 此时我们的Person类的结构不需要有任何变化,如
public class Person{ String name; int age },
然后我们另外定义一个比较器:
public PersonComparator implements Comparator() {..比较Person的大小..},
在PersonComparator里面实现了怎么比较两个Person的大小. 所以,用这种方法,当我们要对一个 personList进行排序的时候,
我们除了了要传递personList过去, 还需要把PersonComparator传递过去,因为怎么比较Person的大小是在PersonComparator
里面实现的, 如:
Collections.sort( personList , new PersonComparator() ).
package com.kk.Collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CompareTest {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>(10);
list.add(new Student(1,"jj"));
list.add(new Student(0,"ww"));
list.add(new Student(0,"kk"));
list.add(new Student(2,"ll"));
Collections.sort(list); //内部比较器:要排序的对象实现Comparable接口,可以对自身进行比较
System.out.println(list);
List<Teacher> t=new ArrayList<Teacher>(10);
t.add(new Teacher(1,12));
t.add(new Teacher(0,13));
t.add(new Teacher(0,14));
t.add(new Teacher(2,15));
Collections.sort(t,new StudentComparator()); //外部比较器:通过实现Comparator接口
System.out.println(t);
}
}
class Student implements Comparable {
int num;
String name;
public Student(int num, String name) {
this.num = num;
this.name = name;
}
@Override
public String toString() {
return "\r\tnum:"+num+" name:"+name+"\r";
}
public int compareTo(Object o) {
Student tmp=(Student) o;
int result=tmp.num>num?1:(tmp.num==num?0:-1);
if (result==0) {
result=tmp.name.indexOf(0)>name.indexOf(0)?1:-1;
}
return result;
}
}
class Teacher{
int num;
double salary;
public Teacher(int num, double salary) {
this.num = num;
this.salary = salary;
}
@Override
public String toString() {
return "\r\tnum:"+num+" salary:"+salary+"\r";
}
}
class StudentComparator implements Comparator{
public int compare(Object o1, Object o2) {
Teacher t1=(Teacher) o1;
Teacher t2=(Teacher) o2;
int result=t1.num>t2.num?1:(t1.num==t2.num?0:-1);
return result=result==0?(t1.salary<t2.salary?1:-1):result;
}
}