How do I reverse an int array in Java?

前端 未结 30 2350
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  你的背包
    2020-11-21 07:55

    Collections.reverse(Arrays.asList(yourArray));
    

    java.util.Collections.reverse() can reverse java.util.Lists 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.

提交回复
热议问题