user1936285 user1936285 - 2 months ago 6
Java Question

Java Reference Object Duplicating

Ok, here is the code I 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 it supposed to print 1 & 2 because I am pushing 10 into the temp variable, not link. But it's printing 1 2 10.

What's actually happening here? Can anyone explain this to me?

Thanks.

Answer

You need to understand what Java references are. They point to objects that live on the heap.

LinkedList<Integer> link = new LinkedList<Integer>();
LinkedList<Integer> temp = link;

When you set the temp equal to link you are equating references. Both point to the same object on the heap. If you modify the object using either reference, the other one sees it as well.

If you want temp to be independent of link, then do this:

List<Integer> link = new LinkedList<Integer>();
List<Integer> temp = new LinkedList<Integer>(link);

Now when you add 10 to temp only its object on the heap will see the change.