Recently reading the introduction to algorithms, when trying to achieve the merger sort, found a very strange problem.
To be able to focus on the problem, use a rewritten code that reproduces the problem. You can try running it.
1 Public classMain2 {3 Public Static voidMain (string[] args)4 {5int[] tmp = {4, 5, 6};6 Test.print (TMP);7 test.test (TMP);8 Test.print (TMP);9 }Ten } One classTest { A Public Static voidTestint[] src) { -int[] out = {1, 2, 3}; - print (out); thesrc =Out ; - print (src); - } - Public Static voidPrintint[] src) { + for(inti:src) { -System.out.print (i + "\ T")); + } A System.out.println (); at } -}
Before I heard that Java is a reference, and in the above example, if the test src = out to the array by element copy, then the last line of output will be 4 5 6, so at first did not think of this problem. However, take this code to ask a senior (in this particular thanks to Fu Cochang), received a reply that Java is the value of the pass. Then he was confused and decided to learn more about it.
After reviewing the relevant data, it is understood that Java is copying pointers when passing parameters, but does not make further copies. Then, this should happen when you execute line seventh of the preceding code:
- Java copies a pointer to the TMP variable, using the copied pointer as src by the test method. Note that the TMP and SRC point to the same object at this point, but they are not the same pointer.
- The program executes all the way to line 16th, when the value of SRC (address) is replaced by out.
- When the 17th line is executed, the SRC is the original out, so it prints 1 2 3.
- The test method is executed and SRC is destroyed.
In the above process, the object pointed to by TMP has not changed because the referenced copy of TMP (that is SRC) was changed. The original src and out object have lost all pointers to themselves and are about to be destroyed shortly thereafter. In the array-by-element replication, SRC is a copy, but the modification to the object it points to depends only on the object pointed to by the pointer and not on the pointer itself, so the modification can be reflected in the TMP.
Reference article: Classic Questions in Java: Passing values and passing references
In addition, recently successfully built a separate blog with VPS, click here to enter.
Problems caused by pass-through, pass-through references (Java)