import java.util.Arrays;
/*
*
* 1) 定义一个Student类(属性:学号、名字、成绩),通过实现comparable接口让它具有比较大小的能力(通过成绩来比较)
2) 定义一个Student数组stus,生成5个Student对象,存入stus中
3) 定义一个StudentTest类,通过调用Arrays工具类中的sort方法来对stus中的元素进行排序。
*/
public class StudentTest {
public static void main(String [] args){
Student [] stu=new Student[5];
stu[0]=new Student(2013014180,"张三",89);
stu[1]=new Student(2013014181,"李四",65);
stu[2]=new Student(2013014182,"王五",78);
stu[3]=new Student(2013014183,"小明",86);
stu[4]=new Student(2013014184,"小华",98);
Arrays.sort(stu);//sort方法可以实现对对象数组排序,但是必须实现 Comparable接口
/*Comparable接口原型为:
* public interface Comparable<T>
* {
* int compareTo(T other);//接口的中方法自动属于public方法
* }
*/
for(Student s:stu){
System.out.println("学号: "+s.getNumber()+" 名字: "+s.getName()+" 成绩: "+s.getScore());
}
}
}
/*
* 因为要实现对Student对象的排序,所以在Student类中要实现Comparable接口,
* 也就是要实现comepareTo()方法
*/
class Student implements Comparable <Student>{
private int number;//学号
private String name;//名字
private double score;//成绩
public Student(int number,String name,double score){
this.name=name;
this.number=number;
this.score=score;
}
public int compareTo(Student other) {
if(this.score<other.score) return -1;
else if(this.score>other.score)return 1;
return 0;
}
public int getNumber() {
return number;
}
public String getName() {
return name;
}
public double getScore(){
return score;
}
}
StudentTest实现Comparable接口
最新推荐文章于 2024-07-10 20:45:48 发布