1. Arrays.sort(T[] a)是对数组元素按字典序进行升序排列
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); System.out.println(Arrays.toString(arr)); } }
output:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo }
[1, 2, 4, 5, 7, 9, 12, 21, 54]
2. Arrays.sort(T[] a, Comparator<? Super T> c)用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>() { public int compare(Integer a, Integer b) { return b-a; } }); System.out.println(Arrays.toString(arr)); } }
output:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo }
[54, 21, 12, 9, 7, 5, 4, 2, 1]
3. Arrays.sort(T[] a, int fromIndex, int toIndex)实现对数组中的一部分进行排序
对数组a中,index属于[fromIndex, toIndex)的元素进行排序
同样,Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? Super T> c)可实现自定义排序规则
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, 2, 7); System.out.println(Arrays.toString(arr)); } }
output:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo }
[5, 4, 2, 7, 9, 12, 54, 21, 1]
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo }
原文地址:https://www.cnblogs.com/macyzhang/p/9861302.html
时间: 2024-10-11 00:59:31