StudentTest实现Comparable接口



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;
   }



}
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值