关于Java官方提供的sort函数的用法

   下面介绍对数组的排序和对动态链表的排序

 

Arrays.sort();

         可以看出这个方法是对基本类型的数组的排序,还可以对自定义类型的对象数组进行排序。下面给出一个实例

int[] nums = new int[]{1,3,2,5,4};
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));

运行结果

ArrayList的sort方法

import java.util.*;

class Student {
    String number;
    String name;
    float score;

    // Constructor
    Student(String number1, String name1, float score1) {
        this.number = number1;
        this.name = name1;
        this.score = score1;
    }

    // Used to print student details in main()
    public String toString() {
        return this.number + " " + this.name + " " + this.score;
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> ar = new ArrayList<Student>();

        Scanner input = new Scanner(System.in);
        int i = 5;
        while (i-- > 0){
            ar.add(new Student(input.next(), input.next(), input.nextFloat()));

        }
        ar.sort((Student s1, Student s2)->{
            return (int)(s1.score - s2.score);
        });

        i = 5;
//        System.out.println(ar);
        while (i-- > 0){
            System.out.println(ar.get(i).number + " " + ar.get(i).name + " " + ar.get(i).score);
        }


        /* 请在这里补全代码,使程序完成指定的功能。 */}
}

运行结果

ArrayList的实例对象ar调用sort方法,向方法里传入一个比较器(用Lambada实现),注意比较器的返回值一定是int类型。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值