Java中Arrays.sort()的三种常用用法(自定义排序规则)

Java中Arrays.sort()的三种常用用法(自定义排序规则)

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 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() {

//重写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{

@Override

public int compare(Integer o1, Integer o2) {

// A.compareTo(B) A>B 返回1,A=B 返回0,A

// compareTo()返回值>0就交换

// 如果02 > o1 就交换 =>降序

return o2.compareTo(o1);

}

}

相关推荐

苹果原装充电器制造商揭秘
beat365体育官网平台

苹果原装充电器制造商揭秘

📅 08-30 👁️ 3428
轻松下载:教你如何在Linux系统中安装软件
365bet手机网址是多少

轻松下载:教你如何在Linux系统中安装软件

📅 08-22 👁️ 2089
明星代言的经典广告案例
beat365体育官网平台

明星代言的经典广告案例

📅 08-17 👁️ 9348