可以直接用Arrays进行数组的排序操作,但对象所在的类必须实现Comparable
Comparable<T>{
comparaTo<T o>();
}
注释:此方法返回一个int类型的数据,此数据只能为三个值:1(表示大于),-1(表示小于),0(表示等于)
package com.compara;
import java.util.Arrays;
public class ComparableDemo01 {
public static void main(String[] args) {
Student[] stu = {
new Student("张三",50,90.0f),
new Student("李四",40,93.0f),
new Student("王五",30,94.0f)
};
Arrays.sort(stu);
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i].toString());
}
}
}
/**
* 继承Comparable
* @author Administrator
*description:先比较得分,年龄相同的按照年龄比较
*/
class Student implements Comparable<Student>{
private String name;
private int age;
private float score;
public Student(String name, int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
/**
* 重写数组的toString()方法
*/
public String toString(){
return name + "\t\t" + this.age + "\t\t" + this.score;
}
@Override
public int compareTo(Student o) {//重写compareTo方法
if(this.score > o.score){
return 1;
}else if(this.score > o.score){
return -1;
}else {
if(this.age > o.age){
return 1;
}else if (this.age < o.age){
return -1;
}else{
return 0;
}
}
}
}
通过修改返回1还是-1就可以实现对student数组的排序。
原理:比较器的排序就是二叉树的排序算法。排序的基本原理,使用第一个元素作为根节点,如果后面的内容比根节点要小,则
放在左子树,如果比根节点要大,则放在右子树。最后遍历节点得到从左到右、从小到大的排序结果。如下图所示:
![](https://img-my.csdn.net/uploads/201303/22/1363944290_1415.jpg)