Home > Net >  What happens when you set two references to the same object equal to each other?
What happens when you set two references to the same object equal to each other?

Time:09-21

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:

enter image description here

End: (The rectangle object below will be recycled by the GC because there is no reference to it)

enter image description here

What you did was a reference change, r1, r2 were pointed to different objects.

  • Related