Comparable接口
Arrays类中存在sort()方法,此方法可以直接对对象数组进行排序
可以直接使用java.util.Array类进行数组的排序操作,但对象所在的类必须实现Comparable接口,用于指定排序接口。
Comparable接口定义如下:
public interface Comparable{public intcompareTo(T o);
}
此方法返回一个int类型的数据,但此int的值只能是一下三种:
1:表示大于 -1:表示小于 0:表示等于
要求:
定义一个学生类,里面有姓名,年龄,成绩三个属性,要求按成绩由高到低排列,如果成绩相等,则按年龄由低到高排序:
class Student implements Comparable { //指定类型为Student
privateString name ;private intage ;private floatscore ;public Student(String name,int age,floatscore){this.name =name ;this.age =age ;this.score =score ;
}publicString toString(){return name + "\t\t" + this.age + "\t\t" + this.score ;
}public int compareTo(Student stu){ //覆写compareTo()方法,实现排序规则的应用
if(this.score>stu.score){return -1;
}else if(this.score
}else{if(this.age>stu.age){return 1;
}else if(this.age
}else{return 0;
}
}
}
};public classTest{public static voidmain(String args[]){
Student stu[]= {new Student("张三",20,90.0f),new Student("李四",22,90.0f),new Student("王五",20,99.0f),new Student("赵六",20,70.0f),new Student("孙七",22,100.0f)} ;
java.util.Arrays.sort(stu) ;//进行排序操作
for(int i=0;i
System.out.println(stu[i]) ;
}
}
};
View Code
孙七 22 100.0王五20 99.0张三20 90.0李四22 90.0赵六20 70.0
注意:
如果在此时Student类中没有实现Comparable接口,则在执行时会出现以下异常:
分析比较器的排序原理
实际上比较器的操作,就是经常听到数据结构中的二叉树的排序算法,通过二叉树进行排序,之后利用中序遍历的方式把内容依次取出来。
排序的基本原理:使用第一个元素作为根节点,之后如果后面的内容比根节点要小,则放在左子树,如果内容比根节点的内容要大,则放在右子树。