The List’s Invariant
These questions are about LinkedList<T>, which owns head, tail, and size as private fields, backed by a private nested class:
public class LinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
private static class Node<T> {
T value;
Node<T> next;
Node<T> prev;
}
}
Solution
Forgetting the reassignment silently lost the change, since head was a variable the caller held and nothing enforced keeping it current. Making head, tail, and size private fields means only the class’s own methods can change them, so the class can guarantee they stay consistent after every operation instead of leaving that to the caller.
Solution
head always points at the first node, tail at the last, and size always equals the number of nodes actually in the list. Every operation that adds a node must keep size in step by incrementing it, and every operation that removes a node must decrement it; skip either update and the invariant breaks, so a later size() call returns a wrong answer.
Solution
Node is private so code outside LinkedList cannot name the type, create one, or read its fields. A caller only calls operations like add, get, and remove, and never needs to know the list is built from nodes. It is static because a node only needs to hold a value and links to its neighbors, not a reference back to a particular LinkedList instance, so tying it to an outer instance would add nothing.
Solution
Encapsulation puts head, tail, and size next to the operations that keep them correct, so the invariant is enforced by the class rather than left to the caller. Information hiding keeps Node and the links private, so callers depend only on what the list does, such as add, get, remove, and the rest, and not on how it is built.