how to make references to the same instance in multiple objects?
Let say I have Class A :
Class A{
public A relative = null;
public int number = 0;
}
and I will create multiple A and those A's relative will be a reference to one of those A.
For example: Let's create four A, so now we have A1, A2, A3, A4.
And the following map will shows (Left Hand Side)'s relative is making reference to (Right Hand Side)
A1 => null,
A2 => A1,
A3 => A1,
A4 => A2
What I want to achieve is: When I modified A1 by (A2.relative.number = 1), and will also "apply" to A3's relative (Which supposed to be a reference to the same instance A1)
So, here are what I have tried:
Using setter:
public void relateTo(A relative){ this.relative = relative; }This doesn't works, since Java is passing reference by value. Where the relative inside the scope of this method is just a copy. So whenever I make any changes to it from outside, it doesn't make changes to this.
Public the variable and direct access it
A2.relative = A1;But nope, this doesn't works.
I have no idea how to achieve this, any ideas?
