SwadhyAI Notes

All Java notes

Java LinkedList Methods Reference

›Short versionOpen if you only have a minute.
  • LinkedList is a List and a Deque. Nodes point at their neighbors. There is no index array.
  • addFirst, addLast, removeFirst, and removeLast work at the ends.
  • get(index) walks from the nearer end. A loop of get(i) is quadratic.
  • poll, pollFirst, and pollLast return null when the list is empty. removeFirst and removeLast throw.
  • Null elements are allowed, so a null from peek can mean empty or a stored null.
  • ArrayDeque is usually the faster deque. It rejects null elements.

LinkedList stores elements in nodes and implements both List and Deque. It shines for queue-like operations at the ends, not for random indexed access.

Methods

APIParametersReturnsBehaviorWatch for
addFirst(E e) / addLast(E e)Element to place at front or back.void.Links a new node at one end of the list.Null elements are allowed, which can confuse peek() null checks.
offer(E e) / offerFirst(E e)Element to enqueue.boolean success.Queue/deque-friendly insertion methods.For LinkedList they usually return true, but Queue APIs allow capacity failure.
poll() / pollFirst() / pollLast()None.Removed element or null if empty.Removes and returns an end element without throwing on empty.Null return is ambiguous if null elements were added.
removeFirst() / removeLast()None.Removed element.Removes from an end.Throws NoSuchElementException when empty.
get(int index)Zero-based index.Element at index.Traverses from the closer end.Repeated indexed loops are inefficient.
descendingIterator()None.Iterator from tail to head.Traverses in reverse order.Use iterator remove rules if mutating while traversing.

Which call fits

OptionBest forTradeoff
LinkedList as QueueSimple FIFO examples and deque operations.ArrayDeque is usually faster and leaner.
ArrayDequeStacks and queues without null elements.No List indexing.
ArrayListIndex-heavy lists.End operations are fast, but front insertions shift elements.

Examples

Use as a queue

java
LinkedList<String> queue = new LinkedList<>();
queue.offer("first");
queue.offer("second");

while (!queue.isEmpty()) {
    System.out.println(queue.poll());
}

Use as a deque

java
LinkedList<String> history = new LinkedList<>();
history.addFirst("current");
history.addFirst("previous");

System.out.println(history.removeFirst()); // previous

A LinkedList is empty. What does poll() return, and what does removeFirst() do?

poll() returns null and does not throw. removeFirst() throws NoSuchElementException. peek() matches poll on the empty case: null, and the list stays empty. If the list is allowed to store null, that null from peek no longer tells you whether the list was empty.