Please Explain this Java Array Reference Parameter Passing Behavior

后端 未结 4 1538
无人及你
无人及你 2021-01-20 15:02
public class TestArray {
    public static void main(String[] args) {
        int[] ar = {1,2,3,4,5,6,7,8,9};

        shiftRight(ar);
        for (int i = 0; i <         


        
4条回答
  •  忘掉有多难
    2021-01-20 15:29

    The problem is that you create a local variable temp array, and you set ar=temp. You need to actually modify the contents of ar, rather than creating a new local array and pointing your copied ar variable to temp

    Try something like this.

    public static void reverseArray(int[] ar) {
        int[] temp = new int[ar.length];
        System.arraycopy( ar, 0, temp, 0, ar.length );
        for (int i = 0, j = temp.length - 1; i < ar.length; i++, j--) {
            ar[i] = temp[j];
        }
    
        for (int i = 0; i < ar.length; i++) {
            System.out.print(ar[i]);
        }
        // prints: 876543219
        System.out.println();
    }
    

提交回复
热议问题