Reputation: 1425
I'm studying linked lists. Again and again I see code which declares a data type of class in the body of the that very class. Here is an example from the book Cracking the coding interview (creating a linked list)
class Node {
Node next = null;
int data;
public Node(int d) { data = d; }
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while (n.next != null) { n = n.next; }
n.next = end;
}
}
In the second line - as you can see 'next' is an instance variable of the type Node, is its own class.
My question is, if I create an instance of the class Node (say X) -
Node X = new Node(10);
The books say that compiler will automatically reserve space for its instance variables (data and next) even if they are not initiated. The (int data = 10) is clearly handled in the constructor, but what happens with next? Seems to me like X will have infinite number of 'next' nodes inside it, because X will have a node inside it named next. And then since every node is supposed to have a data and next part, then next will have its own copy of data and next inside it, and so on and so on.....leading to something like this...
Upvotes: 3
Views: 291
Reputation: 1541
The 'next' Node is simply a reference to a Node object. The fact that space is reserved for the reference to that Node does not mean that a whole new Node is created with sub-Nodes, it just means that the original Node has enough 'room' to store a reference to the other Node. Since 'next' initially has a reference to null, there is 'nothing there' until you initialize a Node and store a reference to it in 'next'.
Basically, a reference to a Node is not the same as a Node.
See Oracle's Documentation on Types, Values and Variables for more information.
Upvotes: 6