How to reverse an array
Short answer
Swap the first and last elements, moving towards the middle:
void main() {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0, j = numbers.length - 1; i < j; i++, j--) {
int tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
}
IO.println(Arrays.toString(numbers));
}Output:
[5, 4, 3, 2, 1]An array of objects
Arrays.asList() gives a view of the array, so Collections.reverse() reverses the array itself:
void main() {
String[] letters = {"a", "b", "c"};
Collections.reverse(Arrays.asList(letters));
IO.println(Arrays.toString(letters));
}Output:
[c, b, a]A new array
If you need the original array unchanged, create a reversed copy with a stream:
void main() {
int[] numbers = {1, 2, 3};
int[] reversed = IntStream.range(0, numbers.length)
.map(i -> numbers[numbers.length - 1 - i])
.toArray();
IO.println(Arrays.toString(numbers));
IO.println(Arrays.toString(reversed));
}Output:
[1, 2, 3]
[3, 2, 1]Common mistake
Running the loop to the end of the array instead of the middle. Each pair is swapped twice, and the array returns to the original order:
void main() {
int[] numbers = {1, 2, 3, 4};
for (int i = 0; i < numbers.length; i++) {
int j = numbers.length - 1 - i;
int tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
}
IO.println(Arrays.toString(numbers));
}Output:
[1, 2, 3, 4]Functions used in this recipe
- Collections.reverse() — Reverses the order of list elements in place.
- List.reversed() — Returns the list in reverse order without copying it.
- Arrays.asList() — Returns a fixed-size list backed by an array.