| 1. First, find out the question: is there a pointer in Java?
Many people would rather not appear in Java as a pointer to the joy and infinite pain that has been brought to us in C and C ++. However, Java actually has pointers. The identifiers of every object (except the basic data type) in Java belong to the pointer type. However, their use is strictly restricted and prevented. They are called handles in <thinking in Java>.
2. Transfer handle
When the handle is passed into a method, it still points to the same object.
Public class testit {
Private string name;
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
Public static void main (string [] ARGs ){
Testit A = new testit ();
A. setname ("");
Testit B = new testit ();
B. setname ("B ");
System. Out. println ("before swap:" + "A =" + A + "name:" + A. getname ());
Swap (A, B );
}
Private Static void swap (testit swap1, testit swap2 ){
System. Out. println ("swaping:" + "A =" + swap1 + "name:" + swap1.getname ());
Testit temp;
Temp = swap1;
Swap1 = swap2;
Swap2 = temp;
}
}
Output result:
Before swap: A = com. Lib. testit @ 16930e2 name:
Swaping: A = com. Lib. testit @ 16930e2 name:
3. Passing a handle will accidentally change the caller's object.
Public class testit {
Private string name;
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
Public static void main (string [] ARGs ){
Testit A = new testit ();
A. setname ("");
Testit B = new testit ();
B. setname ("B ");
System. Out. println ("before swap:" + "A =" + A + "name:" + A. getname ());
Swap (A, B );
System. Out. println ("after swap:" + "A =" + A + "name:" + A. getname ());
}
Private Static void swap (testit swap1, testit swap2 ){
Testit temp;
Temp = swap1;
Swap1 = swap2;
Swap2 = temp;
Swap1.setname ("A's name ");
Swap2.setname ("B's name ");
}
}
Output result:
Before swap: A = com. Lib. testit @ 16930e2 name:
After swap: A = com. Lib. testit @ 16930e2 name: B's name
We can see that A is still the original A, but the name is not the original name!
In the swap () method, swap1 and swap2 exchange each other. In this case, swap2 points to a. Therefore, when setname () is used, the name of a is changed, instead of B's name.
Why?
Liang_chen: The value passed in Java is actually a copy reference, not an object.
Summary:
1: For a value type parameter, the copy of the value is passed.
2: For parameters of the reference type, the copy of the reference itself is passed.
So the key is how you understand the "value" in the passed value. |