- Prerequisites
- Chapters 1–2 · B1V1 7.1 Interfaces
- Covers
- Collection · List · Set · Queue · Deque · Map
- Related
- 4.2–4.5 implementations · Chapter 5 internals · 7.1 Immutable Collections · B2V4 concurrent collections
On this page
1Concept / Definition
The Java Collections Framework is a unified architecture for storing and manipulating groups of objects. It consists of interfaces that describe behaviour (List, Set, Queue, Deque, Map), implementations that provide storage (ArrayList, HashSet, HashMap, ArrayDeque…), and algorithms that operate on them (sorting, searching — Chapter 6). Code is written against the interfaces; implementations can be swapped.


2Why It Exists
Before Java 1.2, Java had only Vector, Hashtable and arrays, each with its own API. The framework introduced common interfaces so that algorithms could be written once, implementations could compete on performance, and developers could learn one vocabulary. The interface-first design is also a direct application of B1V1 7.4: depend on List, not ArrayList.
3Core Concepts
Collection
Collection<E> is the root of the element-based hierarchy: a group of elements with add, remove, contains, size, isEmpty, iterator, stream, removeIf and bulk operations. It extends Iterable<E>, so every collection works with the enhanced for loop. It deliberately says nothing about order or duplicates; the sub-interfaces add those guarantees. Many methods are documented as optional — immutable implementations throw UnsupportedOperationException for mutators.
List
An ordered collection with positional access: elements have indexes, duplicates are allowed, and get(i), set(i, e), add(i, e), indexOf, subList and listIterator are available. Lists define equals as "same elements in the same order". Since Java 21, List extends SequencedCollection, gaining getFirst, getLast and reversed.
Set
A collection with no duplicate elements, where duplicates are determined by equals (and hashCode for hash-based sets) or by compareTo/Comparator for sorted sets. Plain Set makes no ordering promise. SequencedSet (Java 21) adds a defined encounter order, implemented by LinkedHashSet; SortedSet and NavigableSet add sorting and navigation (floor, ceiling, headSet, tailSet), implemented by TreeSet.
Queue
A collection designed for holding elements before processing, usually in FIFO order (LinkedList, ArrayDeque) or priority order (PriorityQueue). Each operation comes in two forms: one throws an exception on failure (add, remove, element), the other returns a special value (offer returns false, poll and peek return null).
Deque
A double-ended queue supporting insertion and removal at both ends: addFirst, offerLast, pollFirst, peekLast and so on. A Deque can act as a FIFO queue or a LIFO stack (push, pop), and ArrayDeque is the recommended replacement for the legacy Stack class. Deque extends both Queue and SequencedCollection.
Map
A mapping from unique keys to values. Map is not a Collection: its elements are pairs, and operations are key-based (get, put, containsKey, remove(key)). It provides three collection views — keySet(), values() and entrySet() — that reflect the map live. SequencedMap (Java 21) adds firstEntry, lastEntry, pollFirstEntry, putFirst and reversed; SortedMap and NavigableMap add key ordering and navigation.

Sequenced collections (Java 21)
JEP 431 filled a long-standing gap: there was no common type for collections with a defined order. SequencedCollection, SequencedSet and SequencedMap now unify first/last access and reversal across List, Deque, LinkedHashSet, TreeSet, LinkedHashMap and TreeMap. reversed() returns a view, not a copy.

4How It Works Internally
Most implementations inherit shared code from skeletal abstract classes — AbstractCollection, AbstractList, AbstractSet, AbstractMap — which implement the interface methods in terms of a few primitive ones (for AbstractList, just get and size). This is the "interface plus optional abstract base class" pattern of B1V1 5.2. Each implementation also declares marker interfaces: RandomAccess tells algorithms that indexed access is fast (ArrayList, not LinkedList), so Collections.binarySearch can choose an indexed or iterator-based strategy.

Figure 5 shows what the skeletal class does for an implementer. AbstractList implements iterator() as a loop over get(i) up to size(), contains and indexOf as scans with equals, subList as a view, and equals, hashCode and toString element by element. A read-only list therefore needs two methods (Example 3); a modifiable one overrides set, and a growable one also overrides add(int, E) and remove(int). The same idea gives AbstractMap, whose subclasses need only entrySet().
Optional operations are the other half of the design. Rather than splitting every interface into a read-only and a mutable version, the framework declares mutators such as add and set on Collection and List and lets an implementation refuse them with UnsupportedOperationException. The interface hierarchy stays small, but the type no longer tells the caller what is allowed: a List<String> may be fully mutable, fixed-size, a read-only view or immutable (Figure 6). Fail-fast iterators complete the picture: each modifiable collection counts structural changes in a modCount field, and its iterators throw ConcurrentModificationException when the count changes under them (6.1).

| Interface | Order | Duplicates | Null elements (typical) | Default implementation |
|---|---|---|---|---|
| List | Positional | Yes | Allowed (ArrayList) | ArrayList |
| Set | None | No | One null (HashSet) | HashSet |
| SequencedSet | Encounter | No | One null (LinkedHashSet) | LinkedHashSet |
| SortedSet / NavigableSet | Sorted | No | No | TreeSet |
| Queue | FIFO or priority | Yes | Usually not | ArrayDeque / PriorityQueue |
| Deque | Both ends | Yes | No (ArrayDeque) | ArrayDeque |
| Map | None | Keys unique | One null key (HashMap) | HashMap |
| SortedMap / NavigableMap | Sorted keys | Keys unique | No null keys | TreeMap |
5APIs / Features / Syntax
List<String> list = new ArrayList<>(); // declare the interface
Set<String> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();
Deque<Task> stack = new ArrayDeque<>();
Queue<Task> fifo = new ArrayDeque<>();
// Common Collection operations
list.addAll(List.of("b", "a", "c"));
list.removeIf(s -> s.startsWith("x"));
boolean has = set.contains("a");
// Sequenced operations (Java 21+)
String first = list.getFirst();
String last = list.getLast();
List<String> backwards = list.reversed(); // view, not copy
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
lhm.putFirst("urgent", 1);
Map.Entry<String, Integer> oldest = lhm.firstEntry();
// Map views
for (Map.Entry<String, Integer> e : map.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}
map.keySet().removeIf(k -> k.isBlank()); // removes from the map itself6Practical Examples

Example 1 — An order book that picks one structure per access pattern
Problem. An order service must find an order by id, list the orders placed in a time window, know which customers are active and show the most recent orders. No single collection does all four well, so the class keeps four, each chosen by the decision in Figure 7.
// Order service choosing collections by requirement
public final class OrderBook {
private final Map<OrderId, Order> byId = new HashMap<>(); // lookup by key
private final NavigableMap<Instant, List<Order>> byTime = new TreeMap<>(); // range queries
// uniqueness
private final Set<CustomerId> activeCustomers = new HashSet<>();
private final Deque<Order> recent = new ArrayDeque<>(); // bounded history
public void add(Order o) {
byId.put(o.id(), o);
byTime.computeIfAbsent(o.createdAt(), t -> new ArrayList<>()).add(o);
activeCustomers.add(o.customerId());
recent.addFirst(o);
if (recent.size() > 100) recent.removeLast();
}
public Collection<List<Order>> between(Instant from, Instant to) {
return byTime.subMap(from, true, to, false).values(); // view
}
}Why it works. Each operation uses the structure built for it: a hash lookup for the id, a subMap range view for the window, a set for uniqueness and a deque bounded at 100 for the history. The four structures must change together, so only add touches them, and between returns a view, which callers must not keep or modify (section 9).
Example 2 — Mini program: the order book end to end
Problem. Run the design of Example 1 with real data: five orders from three customers, ten minutes apart, a history bounded at three, a lookup that hits and one that misses, and a half-open time window.
import java.time.Instant;
import java.util.*;
public class OrderBookDemo {
record Order(long id, String customer, Instant createdAt, int cents) { }
static final class OrderBook {
private final Map<Long, Order> byId = new HashMap<>();
private final NavigableMap<Instant, List<Order>> byTime = new TreeMap<>();
private final Set<String> customers = new HashSet<>();
private final Deque<Order> recent = new ArrayDeque<>();
private final int keep;
OrderBook(int keep) { this.keep = keep; }
void add(Order o) {
byId.put(o.id(), o);
byTime.computeIfAbsent(o.createdAt(), t -> new ArrayList<>()).add(o);
customers.add(o.customer());
recent.addFirst(o);
if (recent.size() > keep) recent.removeLast();
}
Optional<Order> find(long id) {
return Optional.ofNullable(byId.get(id));
}
List<Order> between(Instant from, Instant to) {
return byTime.subMap(from, true, to, false).values().stream()
.flatMap(List::stream).toList();
}
int customerCount() { return customers.size(); }
List<Long> recentIds() {
return recent.stream().map(Order::id).toList();
}
}
public static void main(String[] args) {
Instant t0 = Instant.parse("2026-11-10T09:00:00Z");
OrderBook book = new OrderBook(3);
String[] who = {"asha", "ravi", "asha", "meera", "ravi"};
for (int i = 0; i < who.length; i++) {
book.add(new Order(100 + i, who[i], t0.plusSeconds(600L * i),
1_000 * (i + 1)));
}
System.out.println("find 102 : " + book.find(102).map(Order::customer)
.orElse("none"));
System.out.println("find 999 : " + book.find(999).map(Order::customer)
.orElse("none"));
System.out.println("09:10-09:30 : " + book.between(t0.plusSeconds(600),
t0.plusSeconds(1800)).stream().map(Order::id).toList());
System.out.println("customers : " + book.customerCount());
System.out.println("recent first : " + book.recentIds());
}
}find 102 : asha
find 999 : none
09:10-09:30 : [101, 102]
customers : 3
recent first : [104, 103, 102]Why it behaves this way. The miss returns an empty Optional instead of null, because HashMap.get gives null for an absent key. The window 09:10 to 09:30 is half open, subMap(from, true, to, false), so the order placed at exactly 09:30 (id 103) is excluded, as time ranges usually are. Five orders give three customers because the set ignores repeats, and the deque keeps the newest first and drops the oldest once it holds more than three.
Example 3 — A list from two methods: AbstractList and RandomAccess
Problem. A configuration API must expose a port range such as 8080-8089 as a List<Integer>. Materialising every number wastes memory for large ranges; the list can compute each element instead.
import java.util.*;
public class RangeList extends AbstractList<Integer> implements RandomAccess {
private final int from, to; // [from, to)
RangeList(int from, int to) { this.from = from; this.to = to; }
@Override public Integer get(int index) {
Objects.checkIndex(index, size());
return from + index;
}
@Override public int size() { return to - from; }
public static void main(String[] args) {
List<Integer> ports = new RangeList(8080, 8090);
System.out.println("size " + ports.size());
System.out.println("contains " + ports.contains(8085));
System.out.println("indexOf " + ports.indexOf(8085));
System.out.println("subList " + ports.subList(2, 5));
System.out.println("reversed " + ports.reversed().subList(0, 3));
System.out.println("equals "
+ ports.subList(0, 2).equals(List.of(8080, 8081)));
System.out.println("RandomAccess " + (ports instanceof RandomAccess));
try {
ports.set(0, 1);
} catch (UnsupportedOperationException e) {
System.out.println("set UnsupportedOperationException");
}
}
}size 10
contains true
indexOf 5
subList [8082, 8083, 8084]
reversed [8089, 8088, 8087]
equals true
RandomAccess true
set UnsupportedOperationExceptionWhy it behaves this way. Only get and size are written; contains, indexOf, subList, equals and, since Java 21, reversed all come from AbstractList and work through those two methods. Equality is defined by the List contract, so the computed list equals a List.of with the same elements. set is an optional operation the class does not override, so it throws. Implementing RandomAccess costs nothing and tells Collections.binarySearch and similar algorithms that indexed access is cheap.
Example 4 — Which List accepts which mutator
Problem. A method receives a List<String> and adds to it; it works in tests and fails in production with UnsupportedOperationException. The program probes the five kinds of list a caller can pass, and shows the difference between a view and a copy.
import java.util.*;
public class MutabilityProbe {
static String probe(Runnable op) {
try { op.run(); return "ok"; }
catch (UnsupportedOperationException e) { return "UOE"; }
}
static void row(String name, List<String> list) {
System.out.printf("%-26s set:%-4s add:%s%n", name,
probe(() -> list.set(0, "z")), probe(() -> list.add("d")));
}
public static void main(String[] args) {
List<String> backing = new ArrayList<>(List.of("a", "b", "c"));
row("new ArrayList<>(...)", new ArrayList<>(List.of("a", "b", "c")));
row("Arrays.asList(...)", Arrays.asList("a", "b", "c"));
row("Collections.unmodifiable", Collections.unmodifiableList(backing));
row("List.of(...)", List.of("a", "b", "c"));
row("List.copyOf(backing)", List.copyOf(backing));
List<String> view = Collections.unmodifiableList(backing);
List<String> copy = List.copyOf(backing);
backing.add("d");
System.out.println("after backing.add(\"d\"): view " + view
+ ", copy " + copy);
}
}new ArrayList<>(...) set:ok add:ok
Arrays.asList(...) set:ok add:UOE
Collections.unmodifiable set:UOE add:UOE
List.of(...) set:UOE add:UOE
List.copyOf(backing) set:UOE add:UOE
after backing.add("d"): view [a, b, c, d], copy [a, b, c]Why it behaves this way. Arrays.asList is fixed-size: it writes through to the array, so set works and add cannot. Collections.unmodifiableList is a read-only view, so the later add on the backing list shows through it; List.copyOf made an immutable copy and still shows three elements. A method that needs to modify a list should create its own (new ArrayList<>(input)), and a method that returns one should document which kind it is (Figure 6).
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Declaring ArrayList/HashMap types in fields and APIs | Implementation locked in: every caller depends on ArrayList, so changing it later breaks the API | Declare List, Map, Set and construct the implementation in one place |
| Choosing by habit (always ArrayList/HashMap) | Wrong complexity for the access pattern, e.g. contains() on a large ArrayList inside a loop is O(n²) | Choose by operations needed: list the operations and their frequency first (Figure 7) |
| Modifying a collection while iterating over it | ConcurrentModificationException on the next call to next(), or silently skipped elements with an index loop | Iterator.remove, removeIf (6.1) |
| Assuming views are copies | Unexpected changes, or CME: later changes to the map show up in the "copy", and its own changes alter the map | Copy explicitly: List.copyOf(map.values()) when a snapshot is needed |
| Using legacy Vector, Hashtable, Stack | Needless synchronisation, old APIs; Vector and Hashtable lock on every call, and Stack inherits Vector's index methods | ArrayList, HashMap, ArrayDeque |
| Calling mutators on List.of results | UnsupportedOperationException at run time, often only on a rarely used path | Know which collections are immutable (7.1); copy into new ArrayList<>(...) before modifying (Example 4) |
| Returning an internal collection from a getter | Callers can add or remove elements and break the object's invariants | Return List.copyOf(...) or an unmodifiable view, and document which |
| Treating Collections.unmodifiableList as a snapshot | It is a view: changes to the backing list still show through it | Use List.copyOf for a snapshot (Example 4) |
8Performance & Production Considerations
| Operation | ArrayList | LinkedList | HashSet/HashMap | TreeSet/TreeMap | ArrayDeque |
|---|---|---|---|---|---|
| Add at end / put | O(1)* | O(1) | O(1) avg | O(log n) | O(1)* |
| Get by index / key | O(1) | O(n) | O(1) avg | O(log n) | — |
| Contains | O(n) | O(n) | O(1) avg | O(log n) | O(n) |
| Remove from middle / by key | O(n) | O(n) find + O(1) | O(1) avg | O(log n) | O(n) |
| Iterate | fast | slower | O(capacity + n) | O(n) | fast |
* amortised. Memory matters as much as complexity at scale: every element of a boxed or linked structure is a separate object (B1V1 3.5, Chapter 5), and collections that grow without bound — caches, registries, histories — are the most common cause of OutOfMemoryError in services.
9Architecture & Design Considerations
- Program to interfaces in fields, parameters and return types; choose implementations in one place.
- Expose read-only views or immutable copies from domain objects (B1V1 5.1, 7.2).
- Name domain collections: an
OrderLinesclass wrapping a List can enforce invariants and hides the implementation. - Choose by access pattern: key lookups → Map; uniqueness → Set; ordered ranges → NavigableMap; work items → Queue/Deque.
- Concurrency is a separate axis: none of the classes in this chapter except CopyOnWriteArrayList and BlockingQueue implementations are thread-safe (B2V4).
10Interview Questions & Answers
What are the main interfaces of the Collections Framework?
Collection (with List, Set, Queue and Deque beneath it, plus the sequenced and sorted variants) and the separate Map hierarchy (SequencedMap, SortedMap, NavigableMap).
What is the difference between List and Set?
A List is ordered by position and allows duplicates; a Set contains no duplicates as determined by equals (or comparison for sorted sets) and, in general, has no positional access.
Why does Map not extend Collection?
Its contents are key–value pairs with key-based operations; Collection's element-based methods such as add(E) do not fit. Instead Map offers keySet, values and entrySet views that are collections.
What did sequenced collections add in Java 21?
SequencedCollection, SequencedSet and SequencedMap interfaces providing uniform getFirst/getLast, addFirst/addLast, removeFirst/removeLast and reversed views across List, Deque, LinkedHashSet, TreeSet, LinkedHashMap and TreeMap.
What is the difference between offer/poll/peek and add/remove/element in Queue?
The first group returns special values on failure — false or null. The second throws exceptions (IllegalStateException for a full bounded queue, NoSuchElementException for an empty one).
What is a collection view, and what are the risks?
A collection backed by another, such as keySet(), subList() or reversed(). Changes flow both ways and no copy is made. Risks: unexpected modification of the underlying collection, and ConcurrentModificationException if the backing collection is structurally modified while a view is used.
What does the RandomAccess marker interface do?
It signals that indexed access is fast (constant time), so algorithms like binarySearch or shuffle can use get(i) instead of iterators. ArrayList implements it; LinkedList does not.
A service's heap grows steadily over days. Which collection-related causes would you check first?
Unbounded caches and maps held by singletons or static fields, listener registries never cleared, per-request data accumulated in long-lived collections, and memoisation maps keyed by unbounded inputs. A heap dump's dominator tree usually points to one such collection.
How do you decide between returning a List, a Collection, a Set or an Iterable from a public API?
Return the most specific type that reflects real guarantees callers may rely on — List if order and duplicates matter, Set for uniqueness — but not more; Collection or Iterable leave freedom to change implementation. Always document mutability, and prefer immutable results.
How would you design the in-memory data structures for an order book that needs lookup by ID, time-range queries and a recent-orders feed?
HashMap by ID for O(1) lookup, a TreeMap (NavigableMap) keyed by timestamp for range queries via subMap, and a bounded ArrayDeque for recent orders. Encapsulate them in one class that updates all structures together and exposes read-only views.
What collection-related standards would you set for a large Java platform?
Interfaces in signatures; immutable collections at API boundaries; no legacy Vector/Hashtable; every long-lived collection bounded or evicting and monitored; capacity hints for large maps; primitive or specialised structures for very large numeric data; and explicit choice of concurrent collections for shared state, reviewed in design documents.
What does this program print?
import java.util.*;
public class ViewQuiz {
public static void main(String[] args) {
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("pen", 0);
stock.put("ink", 7);
stock.put("pad", 0);
Set<String> names = stock.keySet();
stock.values().removeIf(v -> v == 0);
System.out.println(names);
names.remove("ink");
System.out.println(stock.isEmpty());
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
List<Integer> back = nums.reversed();
nums.add(4);
System.out.println(back);
}
}It prints [ink], then true, then [4, 3, 2, 1]. keySet() and values() are live views of the map: removing the zero values through values() removes their entries, so the key set already shows only ink, and removing ink through the key set empties the map. reversed() is also a view, so the element added to nums afterwards appears first in back.
What is the difference between Collections.unmodifiableList(list) and List.copyOf(list)?
unmodifiableList wraps the list in a read-only view: callers cannot change it, but changes made through the original reference still show through, so it is not a snapshot. List.copyOf creates an immutable copy, unaffected by later changes, rejects null elements, and returns the argument itself when it is already an immutable list. Use the view to give read access to state you keep changing, and the copy at API boundaries and in value objects (Example 4).
How does AbstractList let a class implement List with only get and size?
Every other method is written in terms of those two. The iterator keeps a cursor and calls get(cursor) until it reaches size(); contains and indexOf scan with equals; subList returns a view that offsets indexes; equals, hashCode and toString walk the elements. Mutators throw UnsupportedOperationException until the subclass overrides set, add(int, E) and remove(int). This is the interface plus skeletal class pattern (Figure 5); for a linked structure, AbstractSequentialList does the reverse and builds get from a list iterator.
Your team wants all service APIs to return Collection or Iterable, never List or Set, to keep implementations free. Do you agree?
Partly. Returning the most general type keeps the implementation free, but it also hides guarantees that callers need: Collection says nothing about order or duplicates, so callers copy into a List defensively, or rely on an order that the next release may change. Iterable cannot even report its size. A better rule is to return the most specific interface whose guarantees you are willing to keep for ever, such as List when order is part of the contract and Set when uniqueness is, always immutable, and to keep concrete classes out of signatures.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- Interfaces describe behaviour; implementations provide storage; algorithms work on interfaces.
- List = positional; Set = unique; Queue/Deque = processing order; Map = key → value (not a Collection).
- Java 21 sequenced interfaces unify first/last/reversed.
- Views are live, not copies.
- Choose by access pattern, bound long-lived collections, program to interfaces.