How do I reverse an int array in Java?

前端 未结 30 2532
爱一瞬间的悲伤
爱一瞬间的悲伤 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:53

    There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:

        int[] a = {8, 6, 7, 5, 3, 0, 9};
        int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
    

提交回复
热议问题