For example, let's say we have a code snippet as follows:
Rectangle r1 = new Rectangle( 5 );
Rectangle r2 = new Rectangle( 10 );
Rectangle r3 = r1;
r1.length = 30;
r1 = r2;
r2 = r3;
r1 = r2;
What exactly is happening when we set r1 to r2 and r2 to r3? Does everything that happens to r2 then happen to r1, etc.?
CodePudding user response:
Rectangle r1 = new Rectangle( 5 ); // A
Rectangle r2 = new Rectangle( 10 ); // B
Rectangle r3 = r1; // r3 = A
r1.length = 30; // Mutate A
r1 = r2; // r1 = B
r2 = r3; // r2 = A
r1 = r2; // r1 = A
Reassigning a variable with will just change the value to which that variable points to.
In the end we can see all 3 variables will point to A
and B
reference will be lost.
CodePudding user response:
At first:
End: (The rectangle object
below will be recycled by the GC because there is no reference to it)
What you did was a reference change, r1, r2 were pointed to different objects.