Reversing an Array in Java [duplicate] Reversing an Array in Java [duplicate] arrays arrays

Reversing an Array in Java [duplicate]


Collections.reverse() can do that job for you if you put your numbers in a List of Integers.

List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);System.out.println(list);Collections.reverse(list);System.out.println(list);

Output:

[1, 4, 9, 16, 9, 7, 4, 9, 11][11, 9, 4, 7, 9, 16, 9, 4, 1]


If you want to reverse the array in-place:

Collections.reverse(Arrays.asList(array));

It works since Arrays.asList returns a write-through proxy to the original array.


If you don't want to use Collections then you can do this:

for (i = 0; i < array.length / 2; i++) {  int temp = array[i];  array[i] = array[array.length - 1 - i];  array[array.length - 1 - i] = temp;}