代码语言:javascript复制
package snippet;
import java.util.Arrays;
/**
* 使用Comparable接口:让待排序对象所在的类实现Comparable接口,并重写Comparable接口中的compareTo()方法
* 缺点是只能按照一种规则排序
* @author tong
*
*/
public class Compara {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] =new Person("tom",45);
persons[1] =new Person("jack",12);
persons[2] =new Person("bill",21);
persons[3] =new Person("kandy",34);
persons[4] =new Person();
//关键
Arrays.sort(persons);
for (Person person:persons) {
System.out.println(person);
}
}
}
下面是继承Comparable的Person类:
代码语言:javascript复制package snippet;
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public Person(){
this("unknown", 0);
}
//重写Student类的toString()方法,在输入对象时按照以下方式输出
@Override
public String toString() {
return "Person[name:" name ",age:" age "]";
}
//重写该类的compareTo()方法,使其按照从小到大顺序排序
@Override
public int compareTo(Person o) {
return age-o.age;
}
}
输出结果:
代码语言:javascript复制Person[name:unknown,age:0]
Person[name:jack,age:12]
Person[name:bill,age:21]
Person[name:kandy,age:34]
Person[name:tom,age:45]