Skip to the page

Collections and generics · core

Choosing a List, and removing items safely

ArrayList is the default list. LinkedList is rarely better. Removing from a list inside a for-each loop throws or skips items.

The notes

What you must know

  • ArrayList is backed by an array. get(i) is O(1). Add at the end is amortised O(1). Insert or remove in the middle shifts elements.
  • LinkedList: get(i) walks the list, O(n). Each node is a separate object with two links, so memory use is high and CPU-cache use is poor. In practice ArrayList wins almost always.
  • For queues and stacks use ArrayDeque (no nulls). Between threads use a BlockingQueue.
  • Pre-size with new ArrayList<>(expected) when you know the size.
  • Java 21 sequenced collections add getFirst, getLast and reversed to List and others.
  • for-each uses an Iterator. Calling list.remove(o) inside it changes the modification count and the next call throws ConcurrentModificationException.
  • Edge case: removing the second-to-last element ends the loop quietly and leaves one element unchecked. The check is best-effort.
  • Fixes: removeIf, an explicit Iterator with it.remove(), a new filtered list, or filter in the query. An index loop with remove(i) skips the next element. Fail-fast iterators (ArrayList, HashMap) versus snapshot (CopyOnWriteArrayList, which copies the array on every write).

The red pen

Common traps: mistake → fix

  • Mistake: LinkedList is faster for inserts

    Fix: only once you hold the node; getting there is O(n).

  • Mistake: ConcurrentModificationException means another thread

    Fix: it usually means you changed the list in the same loop.

  • Mistake: A for-each remove is safe for the last item

    Fix: removing at certain positions silently skips elements.

Easy to hard

Questions interviewers ask, easy to hard

  1. When would you choose LinkedList over ArrayList?
  2. Why does this loop throw ConcurrentModificationException?
  3. Why does it sometimes not throw and leave an expired order behind?
  4. What is a good replacement for a manual remove loop?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview