Java 中的Comparable接口

Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或 Arrays.sort进行自动排序。

    此外,实现此接口的对象可以用作有序映射中的键或有序集合中的集合,无需指定比较器。

    此接口只有一个方法compare,比较此对象与指定对象的顺序,如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。用法如下:

       首先第一步,在要排序的类上实现Comparable接口:

class  student  implements  Comparable<student> {

int  studentScore;

String  studentName;

public student  (String  studentName , int studentScore){

      this. studentScore = studentScore;

      this. studentName = studentName;

}

/**

     * 然后第二步,在要排序的类中实现Comparable接口中的compareTo方法  

     */

    @Override

   public int compareTo(PersonComparable o) {

         // 从小到大排序 this‐o

         // 从大到小排序 o‐this   

//o 表示和当前对象比较的另外一个对象

if(this. studentScore!= o. studentScore){

          return o. studentScore - this. studentScore;

      }else{

          return this. studentName - o. studentName;

   }

}

}

下面以list集合为例:下面的代码是写在另一个类的主方法中

List<student> list = new ArrayList<student>();

list.add(new student ("同学A", 90));

list.add(new student ("同学B", 80));

list.add(new student ("同学C", 90));

list.add(new student ("同学D", 85));

list.add(new student ("同学X", 80));

list.add(new student ("同学M", 75));

list.add(new student ("同学E", 75));

 

//第三步 调用sort 排序

Collections.sort(list);

//for循环遍历输出

for (student student: list) {

System.out.println(student. studentName + "\t分数" +

student. studentScore);

}

结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值