Java 中数组排序的方法有:1) 使用 Arrays.sort() 进行快速排序(默认升序);2) 自定义比较器根据特定条件排序;3) 循环移位通过 System.arraycopy() 和 modulo 运算移动数组元素。此外,还有 Collections.shuffle()(随机打乱)、Guava 的 ImmutableList.sortedCopy()(创建排序副本)和 Stream API 的 sorted() 方法(排序流并转换为数组)等方法。
如何使用 Java 对数组进行排列
引言
对数组进行排列是指将数组中元素重新排序,形成特定的顺序。Java 提供了多种方法来实现数组排列。
排序方法
Arrays.sort()
示例:
int[] arr = {5, 2, 8, 3, 1};
Arrays.sort(arr);
// 排序后:{1, 2, 3, 5, 8}自定义比较器
示例:
Comparatorcomp = new Comparator () { @Override public int compare(Integer a, Integer b) { return b - a; // 降序排列 } }; Arrays.sort(arr, comp);
特殊排列
循环移位
示例:
int[] arr = {5, 2, 8, 3, 1};
int steps = 2;
System.arraycopy(arr, arr.length - steps, arr, 0, steps);
System.arraycopy(arr, 0, arr, steps, arr.length - steps);
// 循环移位后:{8, 3, 1, 5, 2}其他方法
对流排序,然后使用 toList() 方法转换为数组。