LinkedList method choice depends on the endpoint, the empty-case contract, and whether removal targets a value or an index.
Java LinkedList method notes
Endpoint pairs
- FIFO: offer or addLast, then poll or pollFirst.
- LIFO: push, then pop; pop throws when empty.
- Read without removing: peekFirst or peekLast returns null when empty.
- Strict endpoint read: getFirst or getLast throws when empty.
- Position: remove(int) returns an element.
- First equal value: remove(Object) returns a boolean.
Costs
Endpoints use O(1) link work. Searching and arbitrary indexing are O(n) in the worst case. A full iterator traversal is O(n). A get(index) loop over the entire list can be O(n²). Each element requires linked-node storage.
Connected lessons
Continue with Java LinkedList: operations, internals and failure cases, Java LinkedList quiz.
Common Mistakes
Null elements make poll and peek results ambiguous. The class does not coordinate access between threads. A shallow copy preserves references to mutable elements.
Remember which result means absence
pollFirst and peekFirst return null for an empty list, while removeFirst and getFirst reject that empty state with an exception. An actual null element makes a null result ambiguous, so an application queue can choose to reject null elements even though LinkedList permits them.
remove(int) returns the removed element at that position. remove(Object) returns whether a first equal value was found and removed. An Integer argument can select different behavior depending on whether the call supplies a primitive int or an explicitly boxed value; read the argument type before explaining the result.
Iterator traversal follows links once. Repeated get(i) asks for a new location search on each call. A shallow copy also traverses values to build another membership structure without cloning arbitrary elements. Do not treat fail-fast exceptions as an access-coordination mechanism.
