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?
With Commons.Lang, you could simply use
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.
To reverse an int array, you swap items up until you reach the midpoint, like this:
The way you are doing it, you swap each element twice, so the result is the same as the initial list.
If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.
In case of Java 8 we can also use streams to reverse the integer array as: