rgamber
rgamber

Reputation: 5849

Confusion about Java reference

Say I have a simple Node class:

public class Node {
    public Integer data = null;
    public Node next = null; 

    public Node(int data) {
        this.data = data;
    }
}

Now I create a linked list using this nodes:

    Node n1 = new Node(1);
    Node n2 = new Node(2);
    Node n3 = new Node(3);
    Node n4 = new Node(4);
    n1.next = n2;
    n2.next = n3;
    n3.next = n4;

This is basically: 1 -> 2 -> 3 -> 4 -> null

So far so good. Now if I am right, n1, n2, n3, and n4 are holding the addresses where the respective instances of Node are stored. So I go ahead, and do this:

n2 = n3;

i.e. put the address that is stored in n3 also into n2.

So I would expect an output list like this: 1 -> 3 -> 4 -> null
But the output I get is still: 1 -> 2 -> 3 -> 4 -> null.

What am I misunderstanding? How is the list still intact?

Upvotes: 1

Views: 92

Answers (2)

kTest
kTest

Reputation: 367

You are basically changing what n2 is referring to not n2.next. n2 and n2.next are references pointing to 2 different objects. You will have to set n1.next to n3 for the behavior you are expecting. But again n2.next will still be pointing to n3.

Upvotes: 3

Matt
Matt

Reputation: 987

The way a linked list works, you only need an intact reference to the first node in order to traverse the list.

All the line n2 = n3 is doing is changing the reference in n2 from node 2 to node 3, the node itself is unchanged.

n1.next() will still equal the 2nd node.

n1.next().next() will equal the 3rd node.

n1.next().next().next will equal the 4th node.

Upvotes: 2

Related Questions