一、Comparable 接口
作用:定义了一个类的两个实例比较大小的方法,以用于排序。
定义:
所在包:java.lang
具体定义:
interface Comparable<T>{
int compareTo(T o);
}
compareTo 方法说明:
1、返回一个负整数、0或正整数以表明当前的对象小于、等于或大于对象o。此方法要保证判断a>b,b>c,则a>c,判断a>b,则b<a等等。
2、compareTo 方法,用于规定两个实例的自然顺序,用于Arrays.sort 或Collections.sort 方法对数组对象或List 对象进行排序。实践:
class Student implements Comparable{
private String name="";
private int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int compareTo(Object o) {
int result=this.age-((Student) o).getAge();
return result;
}
public int getAge(){
return age;
}
//重写toString方法,实现特定输出
public String toString(){
return this.name+":"+this.age;
}
}
public class Main {
public static void main(String[] args){
Student wei=new Student("小韦",22);
Student zheng=new Student("小郑",21);
Student xia=new Student("小夏",21);
//System.out.print(wei > zheng);并不能直接比较
//对List 或 Array 对象,可通过Collections.sort(List对象) 与Arrays.sort(数组对象)方法
//调用对象的compareTo 方法排序
Student[] stu=new Student[2];
stu[0]=wei;
stu[1]=zheng;
Arrays.sort(stu);
System.out.print(stu[0]);//输出结果为:"小郑:21"而非添加时的第一个元素
System.out.print(zheng.equals(xia));//输出结果为:false,可见Comparable接口与equals
//没有必然联系,但equals 值为true时,必须保证compareTo 值为0 。(可忽略)
}
}
普通的对象是无法排序的,通过实现Comparable 接口规定排序规则。之后,通过Arrays.sort 或Collections.sort 方法排序。
注:java 中的基本数据类型对应对象、Date、Year、Month、Time、DayOfWeek 等多数类都实现了此接口。
参考:http://blog.csdn.net/nvd11/article/details/27393445