I am trying to reverse an int array in Java.
This method does not reverse the array.
for(int i = 0; i < validData.length; i++) { int temp = validData[i]; validData[i] = validData[validData.length - i - 1]; validData[validData.length - i - 1] = temp; }
What is wrong with it?
In Java, the reverse method, which is part of the existing Collections framework, can be used to reverse an array. Let's use it to do the reversal.
There are three ways to reverse a number in Java: Reverse a number using while loop. Reverse a number using for loop. Reverse a number using recursion.
To reverse an int array, you swap items up until you reach the midpoint, like this:
for(int i = 0; i < validData.length / 2; i++) { int temp = validData[i]; validData[i] = validData[validData.length - i - 1]; validData[validData.length - i - 1] = temp; }
The way you are doing it, you swap each element twice, so the result is the same as the initial list.
With Commons.Lang, you could simply use
ArrayUtils.reverse(int[] array)
Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.
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