[JAVA]有关Java中Arrays.sort()的用法

平常,作为静态类Arrays中的静态方法sort()经常被我们使用。但是你知道怎么控制它排序按照正序还是逆序呢?

其实,可以通过使用Comparable接口//Comparator接口,实现compareTo() / /compare()方法来调整正序还是逆序。

代码如下:

首先创建一个StudentCoparable类使用Comparable接口,并实现方法compareTo();

public class StudentComparable implements Comparable<StudentComparable>{  
    private String number;  
    private String name;  
    private int age;  

    public int compareTo(StudentComparable student) {  
            return Integer.parseInt(this.number)-Integer.parseInt(student.number);  
    }  

然后我们开始测试数据,

import java.util.Arrays;  
public class Test {  
    public static void main(String[] args) {  
        StudentComparable sc = new StudentComparable("10000", "lz", 18);  
        StudentComparable sc1 = new StudentComparable("10001", "wx", 18);  
        StudentComparable sc2 = new StudentComparable("10003", "zh", 18);  
        StudentComparable sc3 = new StudentComparable("10002", "gd", 18);  
        StudentComparable scs[] = new StudentComparable[]{sc,sc1,sc2,sc3};  
        Arrays.sort(scs);//正序排序  
        for (int i = 0; i < scs.length; i++) {  
            System.out.println(scs[i].getNumber()+","+scs[i].getName()+","+scs[i].getAge());  
        }  
    }  
}  

此时,测试结果为:
可见是正序排序。

那如果想要逆序排序呢?其实很简单,只需要把compareTo中的

return Integer.parseInt(this.number)-Integer.parseInt(student.number);  

//换个位置

return Integer.parseInt(student.number)-Integer.parseInt(this.number); 

即可变为逆序排序。

其中,Comparator接口也是相同,只需修改compare中的返回值,就可以调整正逆序输出了!!

结论:Arrays中的sort()方法,是跟Comparable接口,Comparator接口有密切相关,如果将来想使用这两个接口和Arrays.sort()方法,值得注意一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值