Reversing an Array in Java [duplicate]

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?


Solution 1:

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]

Solution 2:

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.

Solution 3:

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;
}

Solution 4:

I like to keep the original array and return a copy. This is a generic version:

public static <T> T[] reverse(T[] array) {
    T[] copy = array.clone();
    Collections.reverse(Arrays.asList(copy));
    return copy;
}

without keeping the original array:

public static <T> void reverse(T[] array) {
    Collections.reverse(Arrays.asList(array));
}

Solution 5:

try this:

public int[] reverse3(int[] nums) {
    int[] reversed = new int[nums.length];
    for (int i=0; i<nums.length; i++) {
        reversed[i] = nums[nums.length - 1 - i];
    }
    return reversed;
}

My input was:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

And the output I got:

12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1