Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
PHZE OXIDE Avatar asked Oct 01 '12 18:10

PHZE OXIDE


People also ask

How do you reverse an array without creating a new array?

Reverse an array of characters without creating a new array using java. If you want to reverse int array, you have to change public static void reverseArray(String[] array) as public static void reverseArray(int[] array) and String temp as int temp . Show activity on this post.

What is the method to reverse an array?

prototype. reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.

Does Reverse change the original array?

The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


1 Answers

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] 
like image 102
Vikdor Avatar answered Oct 01 '22 06:10

Vikdor