Reversing an Array in Java

PHZE OXIDE picture PHZE OXIDE · Oct 1, 2012 · Viewed 192.9k times · Source

If I have an array like this:

1 4 9 16 9 7 4 9 11 

What is the best way to reverse the array so that it looks like this:

11 9 4 7 9 16 9 4 1 

I have the code below, but I feel it is a little tedious:

public int[] reverse3(int[] nums) {
    return new int[] { nums[8], nums[7], nums[6], nums[5], num[4],
                       nums[3], nums[2], nums[1], nums[0] };
}

Is there a simpler way?

Answer

Vikdor picture Vikdor · Oct 1, 2012

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]