To reverse an array in Java, turn the array into a
List
, then do Collections.reverse
, finally convert back to array with list.toArray
.Here's how you do it:
String[] array = new String[] { "A", "B", "C" };
java.util.List<String> listFromArray = java.util.Arrays.asList(array);
java.util.Collections.reverse(listFromArray);
String[] reversedArray = listFromArray.toArray(String[]::new);
System.out.println(java.util.Arrays.toString(reversedArray)); // [C, B, A]
Primitive arrays
Here's how you do it if your array is int[]
:
int[] array = new int[] { 1, 2, 3 };
for (int i = 0; i < array.length / 2; i++) {
int item = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = item;
}
System.out.println(java.util.Arrays.toString(array)); // [3, 2, 1]
Here's how you do it if your array is double[]
:
double[] array = new double[] { 1.0, 2.0, 3.0 };
for (int i = 0; i < array.length / 2; i++) {
double item = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = item;
}
System.out.println(java.util.Arrays.toString(array)); // [3.0, 2.0, 1.0]