简体   繁体   中英

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.

Java only has primitive and reference variable types. Your variables

LinkedList<Integer> link = new LinkedList<Integer>(); // reference to a list
LinkedList<Integer> temp = link; // another reference to the same list.

You only created one new LinkedList, so whether you use one reference or the other you still have one list.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM