在Java中,反转数组可以通过以下几种方法实现:
使用循环
public static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
使用临时数组
public static int[] reverseArray(int[] arr) {
int[] result = new int[arr.length];
int index = 0;
for (int i = arr.length - 1; i >= 0; i--) {
result[index] = arr[i];
index++;
}
return result;
}
使用Collections.reverse()方法 (适用于对象数组):import java.util.Arrays;
import java.util.Collections;
public static void reverseArray(Integer[] arr) {
Collections.reverse(Arrays.asList(arr));
}

import java.util.Arrays;
import java.util.Collections;
public static void reverseArray(Integer[] arr) {
Collections.reverse(Arrays.asList(arr));
}

使用StringBuilder.reverse()方法(适用于字符串数组):
public static String[] reverseArray(String[] arr) {
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.reverse().toString().split("");
}
使用栈
import java.util.Stack;
public static void reverseArray(String[] arr) {
Stack
stack = new Stack<>(); for (String s : arr) {
stack.push(s);
}
for (int i = 0; i < arr.length; i++) {
arr[i] = stack.pop();
}
}
以上方法可以根据具体需求选择使用。需要注意的是,对于基本数据类型数组(如int[]),应使用相应的包装类(如Integer[])来使用Collections.reverse()方法。对于字符串数组,可以使用StringBuilder来辅助反转