可在 Java 中逆转数组,方法包括:1. 使用 Collections.reverse() 方法;2. 使用 for 循环;3. 使用递归。Collections.reverse() 效率最高,其次是 for 循环,递归相对较慢。

如何在 Java 中逆转数组
1. 使用内置的 Collections.reverse() 方法
int[] arr = {1, 2, 3, 4, 5};
Collections.reverse(Arrays.asList(arr));2. 使用 for 循环
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}3. 使用递归
立即学习“Java免费学习笔记(深入)”;
int[] arr = {1, 2, 3, 4, 5};
public static void reverseArray(int[] arr, int start, int end) {
if (start >= end) {
return;
}
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
reverseArray(arr, start + 1, end - 1);
}性能比较
-
Collections.reverse()方法效率最高。 -
for循环效率较高,但略低于Collections.reverse()。 - 递归相对较慢,尤其对于大型数组。











