Java教程

java sort方法学习过程总结

本文主要是介绍java sort方法学习过程总结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

参考链接:数组排序

一、对于int[]型数组

调用方法:(注意:默认升序排序)

int[]nums=new int[5];
nums[0] = -7;
nums[1] = -3;
nums[2] = 2;
nums[3] = 3;
nums[4] = 11;
Arrays.sort(nums);
//data数组名

举例:
977.有序数组的平方

public static int[] sortedSquares(int[] nums) {
    int data[] = new int[nums.length]; /*开辟了一个长度为3的数组*/
//        ArrayList<Integer>data=new ArrayList<>();
    for (int i=0;i<nums.length;i++){
        data[i]=nums[i]*nums[i];
    }
    Arrays.sort(data);
    return data;
}

二、对于ArrayList数组

调用方法:(注意:默认升序排序)

List<Integer> list = new ArrayList<Integer>(Arrays.asList(10, 3, 6, 1, 4, 5, 9));
Collections.sort(list);

调用方法:(注意:降序排序)

Comparator<Integer> reverseComparator = Collections.reverseOrder();
Collections.sort(list, reverseComparator);

三、自定义数组存放对象类型

重写compare方法 (注意:升序排序)

//年龄为null时为小
Student studentWang = new Student("王小二", 10);
Student studentZhang = new Student("张三", 1);
Student studentGou = new Student("狗子", 99);
Student studentZhao = new Student("赵六", 40);
Student studentLi = new Student("李四", null);
List<Student> students = new ArrayList<Student>(Arrays.asList(studentWang, studentZhang, studentGou, studentZhao, studentLi));
Collections.sort(students, new Comparator<Student>() {
    public int compare(Student o1, Student o2) {
        if(null == o1.getAge()) {
            return -1;
        }
        if(null == o2.getAge()) {
            return 1;
        }
        return o1.getAge().compareTo(o2.getAge());
    }

compare方法:

  1. return -1时不换位置
  2. return 1 时换位置

compareTo:

  1. 左边<右边时 return -1;
  2. 左边>右边时 return 1;

降序排序

前两种for循环赋给一个新数组

第三种:重写compare方法 (注意:降序排序)

//年龄为null时为最大
Student studentWang = new Student("王小二", 10);
Student studentZhang = new Student("张三", 1);
Student studentGou = new Student("狗子", 99);
Student studentZhao = new Student("赵六", 40);
Student studentLi = new Student("李四", null);
List<Student> students = new ArrayList<Student>(Arrays.asList(studentWang, studentZhang, studentGou, studentZhao, studentLi));
Collections.sort(students, new Comparator<Student>() {
    public int compare(Student o1, Student o2) {
        if(null == o1.getAge()) {
            return 1;
        }
        if(null == o2.getAge()) {
            return -1;
        }
        return o2.getAge().compareTo(o1.getAge());
    }
这篇关于java sort方法学习过程总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!