Search code examples
javasyntaxconstructorlinked-listsimplify

Confusing syntax in Java


I have a piece of code that I'm struggling to comprehend. The code snippet itself is a constructor for a doubly linked list, which is fine; however, the last line says:

(head = head.next).previous = null;

This supposedly removes the temporary node that is used to add the nodes from the array a. But how does it work? If someone could break it down into clear, separate lines, that would be very helpful.

Here is the constructor:

// standard constructor
public DoublyLinkedList() {
    head = tail = null;
    numElements = 0;
    changes = 0;
}

// constructor
public DoublyLinkedList(T[] a) {
    this();  // call the standard constructor

    Objects.requireNonNull(a, "a is null!");

    head = tail = new Node<>(null);  // a temporary node

    for (T value : a) {
        if (value != null) {
            tail = tail.next = new Node<>(value, tail, null);  // new node at the back
            numElements++;
      }
    }

    // remove the temporary node
    if (numElements == 0) head = tail = null;
    else (head = head.next).previous = null; // the problematic bit
}

Solution

  • It goes like this:

    if (numElements == 0) {
         head = null;
         tail = null;
    }
    else {
        head = head.next;
        head.previous = null; // the problematic bit
    }
    

    people should not write the original way, it makes the code confusing, as you just discovered.