0

Why has the array num not changed and the member method shows that num has been changed

public class Code_189 {
    public void rotate(int[] nums, int k) {
        int[] temp;
        for (int i = 0; i < k; i++) {
            temp = new int[nums.length];
            System.arraycopy(nums,0, temp, 1, nums.length-1);
            temp[0] = nums[nums.length-1];
            nums = temp;
        }
        System.out.println(Arrays.toString(nums));
    }

    public static void main(String[] args) {
        Code_189 code_189 = new Code_189();
        int[] nums  = new int[]{1,2,3,4,5,6,7};
        code_189.rotate(nums, 3);
        System.out.println(Arrays.toString(nums));
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    in short: java is pass-by-value - changing the parameter `nums` inside a method will NOT change the variable used when the method was called - this site already has a couple of questions dealing with that, but I am got no time (or too lazy) to search now – user16320675 Apr 10 '22 at 14:37
  • Yes, you're changing the temp array within the method, but then assigning temp to the nums parameter does nothing to the original array object passed into the method. Better to have the method *return* temp, and then assign that result when calling the method: `nums = code_189.rotate(nums, 3);` – Hovercraft Full Of Eels Apr 10 '22 at 14:43
  • Well, @user16320675, this is only part of a solution. You can only change the contents of `num` to be visible outside, but you cannot reassign it and expect the change to be visible outside. – cyberbrain Apr 10 '22 at 14:44
  • 1
    The key concept to gain: if you mutate the array *object* passed into the method, then this will be reflected in the array object passed into the method. If instead you assign the method's array parameter a different array object, then this will have no effect on the array object passed into the method. – Hovercraft Full Of Eels Apr 10 '22 at 14:47
  • @user16320675 of course you can return the new array, but if you want only to rotate the original array, you could do that in the method - unfortunately this question was closed within about 10 minutes, so I could not post an answer how to do that properly :( – cyberbrain Apr 10 '22 at 14:50
  • @user16320675 the OPs code has several problems, so even if Java _would_ work with call by reference, the code would not work to rotate the array. – cyberbrain Apr 10 '22 at 14:51

0 Answers0