Choosing a collection
What you will learn
Choose a collection by the operations your program actually needs. Ordering, uniqueness, mutability, traversal and lookup requirements usually matter more than the name of the implementation.
- Select List, Set, Queue or Deque from concrete requirements.
- Remove elements safely during iteration.
- Distinguish a reversed view from a reversed copy and reason about operation costs.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Remove expired reservations safely
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> days = new ArrayList<>(List.of(2, 0, 5, 0)); Iterator<Integer> it = days.iterator(); while (it.hasNext()) { if (it.next() == 0) it.remove(); } System.out.println(days); }}Expected output:
[2, 5]Each removal follows next on the same iterator; no element is skipped when adjacent removals occur.
Rules and mental model
Use List for ordered positions and repeats; HashSet for membership without ordering; LinkedHashSet for first-seen unique items; TreeSet for sorted membership; ArrayDeque for end-based processing; PriorityQueue for repeated selection of the least-priority element. An Iterable supplies an Iterator with hasNext and next. A supported iterator remove deletes the last item returned by next and is allowed once per next. Do not structurally modify an ordinary collection directly during its iteration unless its documented contract allows it. Many standard iterators detect some concurrent modifications and throw ConcurrentModificationException on a best-effort basis, even in a single thread; this is not synchronization or a correctness guarantee. Java 21 SequencedCollection defines first/last and reversed operations for encounter-ordered collections. Some mutations are optional; reversed often provides a backed view rather than a new collection. In the ArrayList example below, backing list changes are visible in the reversed view. The List interface allows visibility of backing changes to vary by implementation; supported changes through the view write through. Copy the view to capture an independent structure. Complexity describes growth with input size, not actual speed: indexed access on ArrayList is O(1), LinkedList indexing O(n) in the worst case, HashSet membership expected O(1) under proper hashing, TreeSet membership O(log n), and priority-queue insertion/removal of head O(log n). Do not use these costs to promise measured latency. Collection is an interface; Collections is a utility class.
Distinguish a reversed view from a copy
import java.util.*;public class Main {
public static void main(String[] args) { List<String> original = new ArrayList<>(List.of("A", "B")); List<String> reverse = original.reversed(); List<String> snapshot = new ArrayList<>(reverse); original.addLast("C"); System.out.println(reverse); System.out.println(snapshot); System.out.println(original.getFirst()); }}Expected output:
[C, B, A][B, A]AThe reverse view tracks original membership. The copied list has independent membership. These methods require Java 21 or later.
Combine a list, a set and a queue
import java.util.*;public class Main {
public static void main(String[] args) { List<String> scans = List.of("P2", "P1", "P2", "P3"); Set<String> seen = new HashSet<>(); Queue<String> review = new ArrayDeque<>(); for (String id : scans) { if (seen.add(id)) review.offer(id); } System.out.println(scans.size()); while (!review.isEmpty()) System.out.println(review.poll()); }}Expected output:
4P2P1P3The source preserves all scans. The set tests uniqueness while the queue preserves first-arrival processing order.
Common mistakes
A for-each loop hides its iterator, so calling list.remove inside it is unsafe for an ordinary ArrayList. Use an explicit iterator for supported removal, or build a new filtered list. Do not catch ConcurrentModificationException as normal loop control.
Practice
Implement a method that accepts a mutable List<Integer> and removes all negative values with an iterator. Test adjacent negatives, zero, an empty list and an all-negative list. Print each result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choosing a collection — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
When is Iterator.remove legal for a mutable ArrayList iterator?
What happens to an ArrayList reversed view when an item is appended to the original?
Which structure best fits distinct IDs with no required order?
Does fail-fast iteration make a collection thread-safe?
What does new ArrayList<>(source) copy?