Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Creating Two References to the Same Object

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...

like image 398
williamg Avatar asked Jan 12 '12 01:01

williamg


2 Answers

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.

like image 130
Anthony Pegram Avatar answered Oct 21 '22 07:10

Anthony Pegram


Both Lists point to the same Object. Java is passing a reference to the object (by value).

like image 43
calebds Avatar answered Oct 21 '22 09:10

calebds