Java LinkedList and Deque API Reference
LinkedList implements list and deque roles. Choose end operations when the task is a queue, rather than building repeated indexed searches into a linked structure.
Understand the idea
Methods with similar names can have different empty-case contracts. getFirst and removeFirst throw when empty, while peekFirst and pollFirst return null under the usual Deque contract. Because LinkedList itself permits null elements, using null as an empty marker can be ambiguous if callers also store null. Prefer a clear no-null policy for a queue when it simplifies that boundary.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> queue = new LinkedList<>();
queue.addLast("Clay");
queue.addLast("Wood");
System.out.println(queue.getFirst());
System.out.println(queue.removeLast());
System.out.println(queue.pollLast());
System.out.println(queue.pollLast() == null);
}
}
Expected output
Clay
Wood
Clay
truegetFirst inspects without removal. removeLast changes the queue, and the following polls eventually observe an empty state. The explicit final null test demonstrates absence without dereferencing it. Replacing these with arbitrary get(i) calls would hide the end-oriented role and its performance reasoning.
Contracts to look up
| API or language term | What to check |
|---|---|
| add, addAll, addFirst, addLast | Insert through list or deque contracts; indexed forms can require traversal. |
| get, set, getFirst, getLast | Inspect or replace existing values; empty end inspection can throw. |
| remove, removeFirst, removeLast | Remove a selected value/index or an end value with the documented failure behaviour. |
| pollFirst, pollLast, peekFirst, peekLast | Empty-aware deque removal or inspection. |
| contains, indexOf, lastIndexOf | Value search; repeated indexed access is not a constant-time list scan. |
| removeAll, retainAll, removeIf, clear | Membership/predicate-based removal and clearing. |
| size, isEmpty | Logical count and empty-state check. |
| forEach, iterator, listIterator, spliterator | Traversal entry points; read mutation and consistency rules. |
| replaceAll, sort, subList, toArray, clone | Transformation, ordering, backed views and shallow representation copies. |
Check the official Java documentation for detailed contracts and supported options.