Search code examples
javastringmemorylinked-liststorage

Storing One String Value in an empty LinkedList


public class LinkedListExplained {


public Node head;
public Node tail;

public int size;

public LinkedListExplained() { // Constructor
    head = null;
    tail = null;
    size = 0;
}

public class Node{ // Inner Class
    String value;
    Node next;
}

public void add(String value){
    Node node = new Node();
    node.value = value;

    size++;
    if (head == null){
        head = node;
        tail = node;
        return;
    }
    tail.next = node;
    tail = node;

}

Question, when storing a single String value to an empty LinkedList, does it store the same value twice? Once as head and once as tail?


Solution

  • If you are learning Java, the first and foremost thing you need to understand is that in Java, everything that looks like an object is never actually an object; it is a pointer to an object. And of course two pointers may point to the same object.

    So, the statement public Node head; does not declare an instance of Node. It declares a pointer to an instance of Node. That's why you have to use new Node(); later.

    So, since you set both the head and the tail pointers to point to the same instance of Node, it might appear that you have two copies of that node, but in fact you do not. You only have one instance of Node, and you have two pointers pointing at it.