How do I reverse an int array in Java?

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

    This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.

    I hope you glean something from it.

    @Test
    public void reverseTest(){
       Integer[] ints = { 1, 2, 3, 4 };
       Integer[] reversedInts = reverse(ints);
    
       assert ints[0].equals(reversedInts[3]);
       assert ints[1].equals(reversedInts[2]);
       assert ints[2].equals(reversedInts[1]);
       assert ints[3].equals(reversedInts[0]);
    
       reverseInPlace(reversedInts);
       assert ints[0].equals(reversedInts[0]);
    }
    
    @SuppressWarnings("unchecked")
    private static  T[] reverse(T[] array) {
        if (array == null) {
            return (T[]) new ArrayList().toArray();
        }
        List copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
        Collections.reverse(copyOfArray);
        return copyOfArray.toArray(array);
    }
    
    private static  T[] reverseInPlace(T[] array) {
        if(array == null) {
            // didn't want two unchecked suppressions
            return reverse(array);
        }
    
        Collections.reverse(Arrays.asList(array));
        return array;
    }
    

提交回复
热议问题