LinkedList permits null elements, so a null result from peekFirst does not prove that the list is empty.
Java LinkedList null elements: an empty-head ambiguity
This complete Java 8 program has a checked output. Compile it as the named public class, then run it without additional libraries.
Separate absence from payload
A work queue that accepts null cannot distinguish an empty queue from a queue whose first work item is null by calling peekFirst alone. Check isEmpty before reading, or reject null at the application's admission boundary.
getFirst throws on an empty list but returns null when the first stored value is null. That exception is a different contract, not a substitute for explicit input validation. An ArrayDeque rejects null, which removes this particular ambiguity if the application only needs deque operations. See the ArrayDeque lesson before choosing a representation.
Keep the invariant near insertion
The fixture prints the empty and populated states without conflating them. It removes the null element only after checking membership. A real queue should decide whether null is legal before adding a worker, rather than forcing each consumer to guess what null means.
Working program
import java.util.LinkedList;
public class ReceiptQueueNullBoundary {
public static void main(String[] args) {
LinkedList<String> receipts = new LinkedList<>();
System.out.println("empty=" + receipts.isEmpty() + ", head=" + receipts.peekFirst());
receipts.addFirst(null);
System.out.println("empty=" + receipts.isEmpty() + ", head=" + receipts.peekFirst());
System.out.println("removedNull=" + (receipts.removeFirst() == null));
}
}Output
empty=true, head=null
empty=false, head=null
removedNull=trueCosts and boundaries
Endpoint access is constant time; storing n nodes takes linear memory plus per-node references. Null handling changes the API meaning, not those asymptotic costs.
Common Mistakes
- Do not use peekFirst() == null as the sole empty check when null is allowed.
- Do not switch to ArrayDeque while still inserting null.
- Do not hide a null admission policy in each consumer.
Read next
Java LinkedList: operations, internals and failure cases, Java ArrayDeque for queues and stacks, List, set or map?.
