Reputation: 48
So I struggled for quite a while to find documentation about this and failed. The question is more of "How it works" rather than explanation over a snippet of code.
The trouble:
xObject x = new xObject();
yObject y = new yObject( x );
x.add( y );
Where xObject
has:
private ArrayList<yObject> yObjects;
public void add( yObject _y ) {
this.yObjects.add( _y );
}
And yObject
has:
private xObject x;
public yObject( xObject _x ) {
this.x = _x;
}
Now Is it possible to play around with the y
s from the ArrayList inside x?
Trying to figure things out by testing is impossible since whenever I try, I don't seem to have the necessary brain power not to get confused (Reason why I was hoping more intelligent people than me in here may be able to help out).
Upvotes: 1
Views: 209
Reputation: 27190
An ArrayList<yObject>
does not contain yObjects: It contains references to yObjects. The only thing that actually contains any of your objects is the heap.
It's no different from how you can put your friend's name in the "contacts" list on your phone, and she can put your name in the contacts list on her phone. There's no paradox because neither one of your contacts lists contains actual people: The lists only contain information about how to get hold of people. Likewise, Java variables and Java containers don't actually contain objects: They only contain the information needed to find those objects and interact with them.
Upvotes: 3
Reputation: 1738
Yes, you can play with y inside x, because it's reference to object. So if you update y in x, y outside x will be also updated.
Upvotes: 1