How do I reverse an int array in Java?

MichaelScott picture MichaelScott · Jan 26, 2010 · Viewed 553.7k times · Source

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?

Answer

Manur picture Manur · Jan 26, 2010

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.