在Java中,调整数组通常指的是对数组中的元素进行排序、筛选、映射、去重、合并等操作。以下是一些常用的数组调整方法:
排序
使用`Arrays.sort()`方法对数组进行排序。
int[] array = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};Arrays.sort(array);
筛选
使用`Stream.filter()`方法根据条件筛选数组元素。
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int[] evenNumbers = Arrays.stream(numbers).filter(n -> n % 2 == 0).toArray();
映射
使用`Stream.map()`方法将数组中的每个元素转换为新值。
String[] strings = {"one", "two", "three", "four", "five"};String[] upperCaseStrings = Arrays.stream(strings).map(String::toUpperCase).toArray();
去重
使用`Set.copyOf()`方法或`Arrays.stream().distinct().toArray()`去除数组中的重复元素。

int[] arrayWithDuplicates = {1, 2, 3, 4, 5, 1, 2, 3};int[] uniqueArray = Arrays.stream(arrayWithDuplicates).distinct().toArray();
合并
使用`Arrays.copyOf()`方法合并多个数组。
int[] array1 = {1, 2, 3};int[] array2 = {4, 5, 6};int[] combinedArray = Arrays.copyOf(array1, array1.length + array2.length);System.arraycopy(array2, 0, combinedArray, array1.length, array2.length);
交换元素
可以通过创建临时变量或使用索引数组来交换数组中的两个或多个元素。
int[] array = {1, 2, 3, 4, 5};int temp = array;array = array;array = temp;
反转数组
可以通过分半交换元素的方法来反转数组。
int[] array = {1, 2, 3, 4, 5};for (int i = 0; i < array.length / 2; i++) {int temp = array[i];array[i] = array[array.length - 1 - i];array[array.length - 1 - i] = temp;}
请注意,Java中的数组大小是固定的,一旦定义了数组的长度,就无法再进行动态调整。如果需要动态调整数组的大小,可以使用Java集合类中的`ArrayList`
