How do I reverse an int array in Java?

前端 未结 30 2406
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 07:18

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 =          


        
30条回答
  •  -上瘾入骨i
    2020-11-21 08:05

    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.

提交回复
热议问题