Compareble接口
可以直接通过Arrays.sort 对数组进行排序
import java.util.Arrays;
public class Student implements Comparable<Student>
{
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if (this.age < o.age) {
return -1;
}
if (this.age > o.age) {
return 1;
} else {
if (this.score < o.score) {
return -1;
}
if (this.score > o.score) {
return 1;
}
}
return 0;
}
public static void main(String[] args) {
Student stu[]={
new Student("马超", 68, 88),
new Student("赵云", 30, 90),
new Student("关二个", 33, 99),
new Student("张飞",32, 92)
};
Arrays.sort(stu);
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}
输入结果 Student [name=赵云, age=30, score=90]Student [name=张飞, age=32, score=92]
Student [name=关二个, age=33, score=99]
Student [name=马超, age=68, score=88]
如果 Student类没有实现comparable 则会抛出Student cannot be cast to java.lang.Comparable (student类不能被抛到java.lang.Comparable )说明arrays.sort()实现是根据compareble进行数组排序的。引用一老兄的话:java中的对象排序永远都是以Comparable 接口为标准的。、
另一种比较器 comparator
comparator接口中实现的方法
compare(T o1,To2)---比较用来比较的2个参数
compare 主要作用是用来对已经写好的类,但是没有实现comparable 接口进行的补充。
http://blog.csdn.net/cz1029648683/article/details/6666855 一位老兄的文章。