java逆转数组的方法
时间: 2024-12-21 18:11:46 浏览: 5
在 Java 中,有几种方法可以用来逆转数组:
1. **Using Enhanced For Loop (增强for循环)**:
```java
int[] array = {1, 2, 3, 4, 5};
int n = array.length;
for (int i = 0; i < n / 2; i++) {
int temp = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = temp;
}
```
2. **Using Array Copy (数组拷贝)**:
```java
int[] array = {1, 2, 3, 4, 5};
int[] reversedArray = new int[array.length];
System.arraycopy(array, 0, reversedArray, 0, array.length);
List<Integer> list = Arrays.asList(reversedArray);
Collections.reverse(list);
reversedArray = list.toArray(new int[0]);
```
3. **Using Stream API (流API)**:
Java 8 及以上版本引入了流(Stream)API,可以简洁地逆转数组:
```java
int[] array = {1, 2, 3, 4, 5};
int[] reversedArray = IntStream.of(array).toArray();
```
阅读全文