The function parameters in Java are passed by value, and before implementing the interchange of array elements, I would like to start with the Java function parameter passing procedure. In general, we would divide the parameters into basic data types and reference data types, and then pass the arguments separately, because their outward appearance appears to be different, however, their essence is value passing. When talking about value passing, be sure to engrave the five words "copy of the argument" into your mind, as it is the key to understanding the value passing.
// 例子1 int a = 0; void value(int x) { x = 1; } value(a); System.out.println(a); // 结果是 0 // 例子2 StringBuilder a = new StringBuilder("iphone"); void value(StringBuilder str) { str.append("7"); } value(a); System.out.println(a.toString()); // 结果是 iphone7
As you can see from the above results, the first example value is not changed, because only a new value is assigned to the copy of a, and the value of a does not change.
The second example, A is a reference, A's copy and a point to the same memory address, so the calling function is the memory address of the value has changed, so a point of the memory address in the value changed. Our print function prints the value in the memory address pointed to by a, not a itself, and a is still the same.
Here's the code that implements the interchange of array elements, and we'll try to understand it ourselves:
// 交换两个元素 private void exchange(int[] nums, int x, int y) { int temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; }
When the function is called, the operation is a copy of Nums,x and Y, but since both the nums copy and the nums point to the same address, when the function internally operates on the value in memory pointed to by the copy, the value in the memory that the nums points to is also variable, and the Nums reference itself is unchanged. That is, the value in Nums (memory address, such as 0x0029) does not change.
Implementing array element Interchange locations (Flight Understanding Java parameter passing)