How do I reverse an int array in Java?
Solution 1:
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.
Solution 2:
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.
Solution 3:
Collections.reverse(Arrays.asList(yourArray));
java.util.Collections.reverse()
can reverse java.util.List
s and java.util.Arrays.asList()
returns a list that wraps the the specific array you pass to it, therefore yourArray
is reversed after the invocation of Collections.reverse()
.
The cost is just the creation of one List-object and no additional libraries are required.
A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.