一、概述Comparable和Comparator都是用来实现集合中元素的比较、排序的。Comparable是在集合内部定义的方法实现的排序,位于java.lang下。Comparator是在集合外部实现的排序,位于java.util下。Comparable是一个对象本身就已经支持自比较所需要实现的接口,如String、Integer自己就实现了Comparable接口,可完成比较大小操作。自定义类要在加入list容器中后能够排序,也可以实现Comparable接口,在用Collections类的sort方法排序时若不指定Comparator,那就以自然顺序排序。所谓自然顺序就是实现Comparable接口设定的排序方式。
Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足要求时,可写一个比较器来完成两个对象之间大小的比较。Comparator体现了一种策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。总而言之Comparable是自已完成比较,Comparator是外部程序实现比较。
以上部分是转载至:http://www.voidcn.com/article/p-wotrtoif-uq.html,感觉此博客中对Comparable与Comparator区别,文字部分描写的很详细也很清楚,就偷懒复制过来了,对于Comparable与Comparator的比较此博客中也有例子,感兴趣的童靴们可以去看一下。下面的例子是我自己写的,如有不对的地方,还请大家指点。
二、实例
Comparable的用法:
package test;
public class Student implements Comparable{
//学生姓名
private String name;
//学生年龄
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student o) {
if(this.age>o.getAge()){
return 1;//由低到高
}else {
return -1;
}
//return 0;
}
}
测试类:
package test;
public class Test1 {
public static void main(String[] args) {
Student s = new Student();
s.setAge(12);
s.setName("�三");
Student s1 = new Student();
s1.setAge(15);
s1.setName("李四");
s.compareTo(s1);
Student [] stuarray={s,s1};
java.util.Arrays.sort(stuarray);
for(Student stu :stuarray){
System.out.println(stu.getName()+","+stu.getAge());
}
}
}
Comparator的用法:
package test;
public class Student1 {
private String name;
private int age;
public Student1(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package test;
import java.util.Comparator;
public class Student1Comparator implements Comparator{
@Override
public int compare(Student1 o1, Student1 o2) {
if(o1.getName().compareTo(o2.getName())>0){
return 1;
}else{
if(o1.getAge()>o2.getAge()){
return 1;//由低到高
}else{
return -1;
}
//return -1;
}
/*if(o1.getAge()>o2.getAge()){
return 1;//由低到高
}else{
return -1;
}*/
}
}
测试类:
package test;
public class Test1 {
public static void main(String[] args) {
Student1 [] stu1={new Student1("王五",26),new Student1("�柳",15),new Student1("�柳",18),new Student1("�一",12)};
Student1Comparator sc = new Student1Comparator();
java.util.Arrays.sort(stu1,sc);
for(Student1 o3:stu1){
System.out.println(o3.getName()+","+o3.getAge());
}
}
}