How do I reverse an int array in Java?

2018-12-31 02:19发布

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?

30条回答
大哥的爱人
2楼-- · 2018-12-31 03:10
public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}
查看更多
永恒的永恒
3楼-- · 2018-12-31 03:12

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.

查看更多
冷夜・残月
4楼-- · 2018-12-31 03:12
for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }
查看更多
临风纵饮
5楼-- · 2018-12-31 03:13

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.

查看更多
妖精总统
6楼-- · 2018-12-31 03:13

If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.

public static void reverseArray4(int[] array) {
    int len = array.length;
    for (int i = 0; i < len/2; i++) {
        array[i] = array[i] ^ array[len - i  - 1];
        array[len - i  - 1] = array[i] ^ array[len - i  - 1];
        array[i] = array[i] ^ array[len - i  - 1];
    }
}
查看更多
孤独寂梦人
7楼-- · 2018-12-31 03:13

In case of Java 8 we can also use streams to reverse the integer array as:

int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                      .toArray(); //Output: [5, 4, 3, 2, 1]
查看更多
登录 后发表回答