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.
Answer from 3lectrologos on Stack OverflowTo 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.
Why is there no Arrays.reverse() ?
How am I supposed to reverse the elements of an array?
this sounds like homework haha
easy way: make a 2nd array the same length as the original one, then use the for loop you mentioned
cooler way: reverse an array without making a 2nd array
More on reddit.comI tried to add inputs to an array in reverse and printed it. Literal GIBBERISH came out
Sorting an int[] arr in reverse order
Videos
Reversing an array is a common task, however Arrays.reverse() is missing from the standard library. Why? I can do this task manually, but why is it left out from the Arrays class?