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?
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.
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.
The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With