Arrays.sort(int[] a)

这种形式是对一个数组的所有元素进行排序,并且是按从小到大的顺序。

举例如下:

import java.util.Arrays;
  
public class Main {
		public static void main(String[] args) {
          
      	int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        Arrays.sort(a);
        for(int i = 0; i < a.length; i ++) {
             System.out.print(a[i] + " ");
        }
    }
}

0 1 2 3 4 5 6 7 8 9

Arrays.sort(int[] a, int fromIndex, int toIndex)

这种形式是对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序,注意:下标为toIndex的元素不参与排序哦!

举例如下:

import java.util.Arrays;
  
public class Main {
		public static void main(String[] args) {
				int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
				Arrays.sort(a, 0, 3);
        for(int i = 0; i < a.length; i ++) {
        		System.out.print(a[i] + " ");
        }
    }
}

7 8 9 2 3 4 1 0 6 5

Arrays.sort(T[] a, Comparator<? Super T> c)用Comparator接口实现自定义排序规则

实现Comparator接口实现降序

import java.util.*;

public class Main {
    public static void main(String[] args){
      	//不能使用基本数据类型
        Integer[] arr = {5,4,7,9,2,12,54,21,1};
        //降序
        Arrays.sort(arr, new Comparator<Integer>() {
        		//重写compare方法,最好加注解,不加也没事
            public int compare(Integer a, Integer b) {
              	//返回值>0交换
                return b-a;
            }
        });
        System.out.println(Arrays.toString(arr));    
    }   
}

和下面这个等价

import java.util.*;

public class Main {
    public static void main(String[] args){
      	//不能使用基本数据类型
        Integer[] arr = {5,4,7,9,2,12,54,21,1};
        //降序
        Arrays.sort(arr, (a, b) -> {
            //返回值>0交换
            return b-a;
        });
        System.out.println(Arrays.toString(arr));
    }
}

还可以

import java.util.*;

public class Main {
    public static void main(String[] args){
        Integer[] arr = {5,4,7,9,2,12,54,21,1};
        //降序
        //重新实现Comparator接口
        Arrays.sort(arr, new compa());
        System.out.println(Arrays.toString(arr));
    }
}

class compa implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
    	// A.compareTo(B) A>B 返回1,A=B 返回0,A<B 返回-1
      	// compareTo()返回值>0就交换
      	// 如果02 > o1 就交换 =>降序
        return o2.compareTo(o1);
    }
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐