Examine the following code:
Object object = new Object();
objectList.add(object);
objectListTwo.add(object);
Is there any way to get both arrays to point to the same object, such that when I change object
in one array, it changes in the other?
Thanks for your help!
EDIT: Turns, out my above code does exactly that. Problem was elsewhere in my code. My apologies for my confusion...
Depends what you mean by "change." If you mean change as in calling setters and mutating the object, then those changes are observed. If you mean change as in completely reassigning or overwriting the variable (or reference), those changes are not observed.
Put it simpler, say you have one object, one array.
Foo foo = new Foo();
Foo[] foos = new Foo[1];
foos[0] = foo;
The item in the array and the variable each reference the same Foo.
foo.setBar(7);
int bar = foos[0].getBar(); // will get 7
The change to the object referenced by foo is observed inside the array.
foo = new Foo();
foo.setBar(94);
bar = foos[0].getBar(); // will not get 94
This change is not observed inside the array, as foo has been reassigned. Its setter is now mutating a different object entirely.
Both Lists point to the same Object. Java is passing a reference to the object (by value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With