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

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -