Java Reference Object Duplicating -
ok, here code written
public void print( object obj ){ system.out.println( obj.tostring() ); } public main() { linkedlist<integer> link = new linkedlist<integer>(); linkedlist<integer> temp = link; link.push(1); link.push(2); temp.push(10); while( link.isempty() == false ){ print( link.getlast() ); link.removelast(); } }
i guess supposed print 1 & 2 because pushing 10 temp variable, not link. it's printing 1 2 10.
what's happening here? can explain me?
thanks.
you need understand java references are. point objects live on heap.
linkedlist<integer> link = new linkedlist<integer>(); linkedlist<integer> temp = link;
when set temp
equal link
equating references. both point same object on heap. if modify object using either reference, other 1 sees well.
if want temp independent of link, this:
list<integer> link = new linkedlist<integer>(); list<integer> temp = new linkedlist<integer>(link);
now when add 10 temp
object on heap see change.
Comments
Post a Comment