/*比较器用于实现对对象的比较和排序,一个对象要想实现比较和排序的操作该对象所对应的类就必须要实现Comparable类接口.Comparable
* 接口的定义如下:
* public interface Comparable<T>
* {
* public int compareTo(To);//该方法当中用于覆写相关类当中的具体比较操作
* }*/
//设计一个学生类包含姓名年龄成绩,要求按照成绩由高到低进行排序,当成绩相同时按照年龄由低到高进行排序
public class Student implements Comparable<Student>{//指定泛型的类型为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;
}
public String toString()
{
return name+"\t\t"+age+"\t\t"+score;
}
//设定具体的学生类的比较方法,当成绩相同时进行年龄的比较操作
public int compareTo(Student stu)
{
if(this.score>stu.score)
{
return -1;
}
else
{
if(this.score<stu.score)
return 1;
else
{
if(this.age>stu.age)
return 1;
else
{
if(this.age<stu.age)
return -1;
else
return 0;
}
}
}
}
}
public class ComparableDemo01 {
public static void main(String[] args) {
Student stu[]=//建立一个学生类的对象类数组
{
new Student("张三",20,90.0f),
new Student("李四",22,90.0f),
new Student("王五",20,90.0f),
new Student("赵六",20,70.0f),
new Student("孙七",22,100.0f)
};
java.util.Arrays.sort(stu);//对所创建的学生类数组进行排序操作
//对排序后的学生数组对象进行带引输出
for(int i=0;i<stu.length;i++)
{
System.out.println(stu[i]);
}
}
}
运行结果: