此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法,比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。可以称作是一个内部比较器。
看一个例子:
// 定义一个学生类:
package comparabletest;
/**
* @author Administrator 定义一个学生类实现Comparable接口
*/
public class Student implements Comparable<Student> {
private int score;
private int age;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int score, int age) {
this.score = score;
this.age = age;
}
@Override
public int compareTo(Student arg0) {
Student s = (Student) arg0;
if (this.score < s.getScore()) {
return -1; // 自身对象值小于比较对象值,返回-1.按升序排列
} else if (this.score > s.getScore()) {
return 1; // 自身对象值大于比较对象值,返回1.按升序排列
} else {
if (this.age > s.getAge()) {
return -1; // 自身对象值大于比较对象值,返回-1.按降序排列
} else if (this.age < s.getAge()) {
return 1; // 自身对象值小于比较对象值,返回1.按降序排列
} else {
return 0; // 自身对象值等于比较对象值,返回0.
}
}
}
@Override
public String toString() {
return "Student [score=" + score + ", age=" + age + "]";
}
}
// 测试代码,将学生信息排序
package comparabletest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentCompare {
public static void main(String[] args) {
// 定义一个长度为4的数组
Student[] students = { new Student(100, 20), new Student(95, 21),
new Student(93, 22), new Student(95, 24) };
// 按分数升序,按年龄降序排列
java.util.Arrays.sort(students);
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
System.out.println("------");
// 定义一个长度为4的列表
List<Student> studentsList = new ArrayList<Student>();
studentsList.add(new Student(100, 30));
studentsList.add(new Student(99, 40));
studentsList.add(new Student(98, 50));
studentsList.add(new Student(99, 42));
// 按分数升序,按年龄降序排列
Collections.sort(studentsList);
for (Student s : studentsList) {
System.out.println(s);
}
}
}
输出结果:
Student [score=93, age=22]
Student [score=95, age=24]
Student [score=95, age=21]
Student [score=100, age=20]
------
Student [score=98, age=50]
Student [score=99, age=42]
Student [score=99, age=40]
Student [score=100, age=30]