The Question First, Then the Class
The stack of earlier chapters helped us understand how a data structure is built. In a Java application, however, we will almost always use standard library collections. The Java Collections Framework brings together interfaces, implementations and algorithms for managing groups of objects. Its breadth may invite us to memorize a catalog of classes; it is more useful to start from the problem's questions. Are duplicates allowed? Does order matter? Do we access by position, by key or from an end? Must the collection change after creation?
A set, list, stack, queue, deque and map answer different questions. Before choosing a concrete class, let us correct two common shortcuts. A Java list is not necessarily a chain of nodes: ArrayList uses a resizable array, and LinkedList uses links. A Map belongs to the framework but does not extend Collection: it associates keys with values rather than simply containing elements. Figure 17.1 compares the two families without suggesting a false single hierarchy.
Collection and Map answer different needs. Interfaces declare the contract; classes such as ArrayList, LinkedHashSet and LinkedHashMap are concrete choices with their own properties.Definition – Interface and Implementation.
List<String>is a reference type promising list operations.new ArrayList<String>()creates a concrete implementation. Declaring a variable with the interface makes the required contract visible; choosing the class at creation establishes properties such as operation costs and order management.
From the Stack We Built to a Family of Solutions
Think back to the stack implemented in Chapters 7 and 8. It was useful because it forced us to establish a rule: the last element inserted is the first to come out. We had to choose how to store data, how to recognize a full stack and what to do with an empty stack. Now the problem changes. The library must manage more than a single structure: titles in sequence, codes without repetitions, waiting loans and books searchable by code. Writing a new class every time would mean repeating much work and multiplying errors. The framework offers common contracts and ready implementations; our responsibility remains choosing the contract suitable for the problem.
Historically Java already had Vector, Stack and Hashtable, before the framework organized collections around common interfaces. Since Java 5, generics also allow the element type to be expressed, for example List<Book>, without entrusting every read to a cast from Object. We will still encounter those classes in existing programs, but should not automatically use them for new code. The important step is not remembering a date: it is understanding why a family of interfaces makes changing implementation easier when the need remains the same.
Consider List<String> titles = new ArrayList<>();. The left-hand part says that code using titles requests an indexed sequence of strings; the right-hand part chooses a resizable-array representation. If tomorrow we change representation, we can do so only if code does not depend on properties specific to ArrayList. Declaring the interface does not make every implementation equivalent: order, mutability, acceptance of null, operation costs and concurrent behavior remain choices to verify.
To Understand – Three Pieces of the Framework. Interfaces define required behavior:
Listpermits access by position,Setdoes not allow duplicates, andMapassociates keys and values. Implementations store data and realize that behavior:ArrayList,HashSetorHashMap, for example. Algorithms work on collections, such as sorting a list throughCollections.sort. Separating these three parts allows us to ask first what the structure must do, then how best to implement it.
Common Operations Before Concrete Classes
Collection<E> extends Iterable<E> and is the root of the family including lists, sets and queues. For a collection we can ask size(), isEmpty() and contains(element); we can traverse it, add or remove elements if the implementation permits, or convert its contents into an array. Map<K,V> follows a distinct branch: size() and isEmpty() have a similar meaning, but a map element is an association rather than a simple E. When we need to traverse a map, we obtain a view of keys, values or pairs through keySet(), values() and entrySet().
Operations working on whole groups are as important as those on a single element. catalog.containsAll(selected) asks whether every element of selected appears in the catalog; addAll transfers elements from one collection to another; removeAll eliminates those present in the other; retainAll retains only common ones. The Boolean value returned by these modifications indicates whether the collection changed, rather than how many elements were moved. For example, calling addAll with a set of titles already present in a Set leaves the set unchanged and returns false. Not every collection allows modifications: the method signature exists in the interface, but an unmodifiable collection can throw UnsupportedOperationException.
Important note – A Generic Type Does Not Promise Mutability.
Collection<Book>says which type of element we can read without a cast. It does not say thataddwill succeed, thatnullis permitted or that iteration has a stable order. These promises belong to the contract of the concrete collection and the API delivering it. This is why a function receivingCollection<Book>should use only operations it really needs and document whether it intends to modify it.
To avoid confusing structures with their use, think of two concrete questions. “Which titles appear in the reading list, even if repeated?” leads to a List. “Which codes have already been visited?” leads to a Set. The first question assigns meaning to position and repetition; the second to uniqueness. Only afterwards do we decide whether encounter order or search speed requires ArrayList, LinkedHashSet or another implementation. This order of reasoning is a brick we will also use when reaching maps.
Lists: Sequence, Duplicates and Position
A List<E> maintains a sequence of elements and can contain duplicates. get(index) reads a position; index 0 is the first element. In the complete program, new ArrayList<>(List.of("Java", "Nets", "Java")) creates a modifiable list with three elements. The output [Java, Nets, Java] confirms that the second Java is not eliminated. The constructor receives an initial list, but creates a new ArrayList: adding or removing elements from the new list does not change the one passed to the constructor.
ArrayList is often the first choice for a list: access by index is direct and appending is normally efficient, although it may require resizing the internal array. Inserting or removing near the beginning generally requires elements to be shifted. LinkedList has a different structure, but does not automatically become faster for every insertion: reaching the position may cost a traversal and every node requires memory and links. If the problem mainly uses the ends, it is often best to look at Deque before choosing LinkedList out of habit.
The Java 25 documentation for List distinguishes mandatory operations from modification operations that some implementations can reject. A method receiving List cannot infer solely from the static type whether add is allowed. This is why the contract of the API delivering the list must also explain its mutability.
Two Lists, the Same Interface, Different Costs
An ArrayList stores references in an array that can grow. get(0) or get(500) directly reaches the requested position: it does not need to traverse the preceding 500 elements. If we append and internal capacity is sufficient, the operation is simple; when it is not, the list must provide more space and copy references. This occasional cost explains why we talk of amortized cost for appends: many inexpensive additions and a few more costly reallocations. If we insert at position zero, on the other hand, existing elements must shift to make space. Internal capacity does not coincide with size(): a newly created list may have space available while containing zero elements, and the precise capacity value is an implementation detail on which the program should not rely.
A LinkedList stores every element in a node linked to the previous and next one. Adding or removing at an end can avoid shifting many references; reaching position 500, however, requires traversing nodes. Even insertion “in the middle” is fast only after the point has been reached, for example with a ListIterator already positioned there. If for every insertion we call get(index) or add(index, element) starting from the beginning, the cost of finding the point can dominate. Nodes also require space and can worsen data locality in memory. There is therefore no rule “LinkedList is better when modifying a list” without saying how we reach the point to modify.
Figure 17.2 makes visible why the two lists have different costs: in an array a position is identified by its index, while in a linked list references between nodes are followed.
ArrayList reaches a position by index; LinkedList must traverse links to reach an internal node. The drawing represents references between elements, rather than physical sizes in memory.| Need | ArrayList |
LinkedList |
|---|---|---|
Frequently read position i |
Direct access; natural choice. | Requires a path between nodes. |
| Append at the end | Normally inexpensive; occasional growth copies references. | Adds a node at the end. |
| Insert in the middle knowing only the index | Shifts some references. | First reaches the point, then changes links. |
| Use a queue from the ends | Possible with list operations, but the type communicates little of the intention. | Also implements Deque; often ArrayDeque is simpler if indices are unnecessary. |
The table compares operations, rather than declaring an absolute winner. If the library often displays page 20 of a list, ArrayList is plausible. If we need a request queue, the right contract is Deque or Queue: representation is chosen afterwards. Vector is another resizable-array list, born before the framework and with historically synchronized methods. Synchronization of individual methods does not alone solve a compound operation, such as “check whether the title is missing and then add it”. For new code we choose the contract and concurrency policy explicitly, rather than using Vector as a shortcut.
Searching and Working on a Portion
A list is not only for reading an index. indexOf(title) searches for the first position of an element equal according to equals; lastIndexOf(title) searches for the last. If the title is absent, the result is -1, so it must be checked before use as an index. set(i, value) replaces the element at position i if the list supports modification; add(i, value) inserts and shifts subsequent elements; remove(i) removes and returns the element occupying that position. For a list of strings, remove(1) chooses index 1, whereas remove("Java") chooses the first occurrence of the value. With a List<Integer>, the distinction between index and value deserves even greater attention: remove(1) indicates the index, and remove(Integer.valueOf(1)) the value.
subList(start, end) describes a portion with an exclusive end bound, like substring for strings. From List.of("A", "B", "C", "D"), the portion from 1 to 3 contains B and C. It is a view of the list: it is not equivalent to a new independent archive. If the caller must retain a snapshot of titles while the original list keeps changing, it creates an explicit copy. When an element is mutable, even a new list copies only the references to elements, rather than every contained object: the difference between copying the container and copying books returns here in a very concrete form.
Sets: Uniqueness and Order
A Set<E> does not contain two elements equal according to the equality criterion used by the implementation. HashSet uses hashCode and equals: the C10 contract therefore becomes concrete. If two objects are equal according to equals, they must produce the same hash; otherwise the set may not correctly recognize duplicates. Do not promise an iteration order for HashSet. LinkedHashSet, on the other hand, maintains a defined encounter order. In the program, from the list with two Java values we obtain [Java, Nets], then the reversed() view reads [Nets, Java].
TreeSet maintains elements sorted according to their natural order or a Comparator. In the program the comparator sorts first by length and then alphabetically. The values API, Java and Nets are printed in that order. Here the comparator's second part is essential: if we compared only length, Java and Nets would be considered equivalent for the set, which would retain only one. A TreeSet order is not a later decoration: it also decides when two elements occupy the same logical position in the set.
EnumSet is a specialized set for enum values: when the domain is an enum, it makes the type explicit and offers a dedicated implementation. It is not necessary to use it for every set; the choice follows the data type and required operations.
Important note – Three Meanings of “Order”. A list has positions and a sequence order. A
LinkedHashSetpreserves a defined encounter order, but permits neither duplicates nor indexed access. ATreeSetsorts according to a comparator. Merely saying that a collection “is ordered” leaves the decisive question open: according to which rule?
Figure 17.3 compares the promises of the three main Set implementations: all eliminate duplicates, but answer different traversal needs.
HashSet promises no order, LinkedHashSet retains first appearance, and TreeSet uses the comparator. Names in the HashSet box represent members, rather than a print sequence.Set Operations Solve Domain Questions
Suppose we have the codes of books owned by a library and those requested for an exhibition. owned.containsAll(requested) answers “do we have them all?”. If we want codes appearing in at least one of the two groups, we start from a modifiable copy and call addAll: this is union. If we want only common ones, we call retainAll: this is intersection. If we want owned codes that are not requested, we call removeAll: this is difference. The operations modify the set on which they are invoked; to preserve the two starting sets, we create a copy first. The result of containsAll is Boolean and does not change data.
To Understand – Set Notation. If
A = {Java, Nets}andB = {Nets, API}, unionA ∪ BcontainsJava,NetsandAPI; intersectionA ∩ Bcontains onlyNets; differenceA \ Bcontains onlyJava. The symbols are a short way of naming a concrete question. In Java, on a modifiable copy ofA,addAll(B),retainAll(B)andremoveAll(B)respectively implement these three questions. After every call we check which set has changed: we do not want to accidentally alter the original archive.
The fact that HashSet promises no order does not mean that it “sorts by hash”: the order we observe in a print can change and is not a contract to use. LinkedHashSet preserves encounter order, useful when removing duplicates from a list without losing first-appearance order. TreeSet instead applies a comparison rule: if the rule considers two elements equivalent, the second finds no distinct position in the set. This is why a comparator chosen merely for a pleasing print can delete information. If the domain considers two titles of the same length different, the comparator must distinguish them, for example by adding alphabetical comparison.
A Set Built on Enum Values
Let us return to an enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }. If a library opens Monday through Friday, EnumSet.range(Day.MONDAY, Day.FRIDAY) expresses the inclusive range according to the constants' declaration order. EnumSet.noneOf(Day.class) creates the empty set while keeping the type known; allOf(Day.class) takes every day; of(Day.SATURDAY, Day.SUNDAY) chooses two explicit values. copyOf starts from an existing collection, but for a generic empty collection the enum type cannot be derived: in that case we use noneOf and add elements. These factories avoid representing nonexistent days with mistyped strings.
EnumSet does not accept null and is modifiable. It does not automatically become safe for concurrent modifications merely because it is specialized and efficient. If opening hours also depend on holidays, location or season, a static set of days is not enough: the model must include those conditions. This is the generalization step: the EnumSet solution fits “which enum constants belong to the group?”, rather than every temporal rule of the library. The Java 25 specification lists the factories and their error conditions.
Maps: Searching by Key
A Map<K,V> associates a key K with a value V. In a catalog, the key might be the book code and the value its entry. A key appears at most once; calling put again with the same key replaces the associated value. HashMap offers hash-based searching without promising iteration order. LinkedHashMap maintains a defined order. TreeMap sorts keys according to a comparator or their natural order. EnumMap is a specialized choice when keys belong to an enum.
In the program we use SequencedMap<String, Integer> loans = new LinkedHashMap<>();. After inserting Java and Nets, firstEntry().getKey() returns Java; the reversed() view shows Nets as the first entry. The word view matters: a view exposes the same data from a different perspective and can reflect changes to the underlying map, according to the contract of the specific implementation. It should not automatically be mistaken for an independent copy.
For HashMap, keys require a hashCode consistent with equals, as for HashSet. Using a mutable object as key and then changing fields involved in equality and hashing can make the entry difficult to find again. An immutable key, such as a well-chosen record, reduces this risk. If a key can be null, behavior must be checked in the concrete implementation; the Map.of factories do not accept null keys or values.
Figure 17.4 brings together the most common maps: the unique-key rule remains identical first, while the order in which we can visit entries then changes.
HashMap, LinkedHashMap, TreeMap and EnumMap distinguish four traversal needs. The figure assigns no order to HashMap.From the Book Code to Its Entry
The question “is the book with code J-17 available?” differs from “at which position in the list is J-17?”. If the code uniquely identifies the book, a map directly describes the association. put("J-17", entry) records the entry; get("J-17") retrieves the value or null if no entry exists for the key. If null values are allowed by the map, a null returned by get can also mean that the key exists but its value is null: containsKey distinguishes the two cases. A domain API can choose an even clearer model, for example Optional<Book> in C19, if absence is a normal answer.
A second put with the same key replaces the previous value and returns that previous value, or null according to the rules just seen. Size does not increase. This allows a book entry to be updated without creating two competing identities. Values, on the other hand, can repeat: two different codes can have the same category or author. containsValue asks whether at least one entry has that value, but is not a substitute for a key search when the problem requires repeated access performance.
HashMap is a common choice when no traversal-order guarantee is needed. Printing four entries may look ordered in one execution and different in another: we should not deduce that HashMap sorts keys. LinkedHashMap retains a defined encounter order, normally insertion order: if we insert keys 1, 3, 2, 4 and then replace the value of 4, order remains 1, 3, 2, 4 in the ordinary case. TreeMap instead sorts by keys, using their natural order or a comparator. If codes must always appear sorted and the catalog changes continuously, this contract can be useful; if we only need an occasional print, we could sort a view of the keys at presentation time.
| Question | Initial choice | Guarantee to check |
|---|---|---|
| Do I find a book by code without a required traversal order? | HashMap |
Stable key for equals and hashCode; unsynchronized access. |
| Must I remember recording order? | LinkedHashMap |
Promised order is encounter order, rather than automatically alphabetical. |
| Must I always traverse keys in order? | TreeMap |
The comparator must distinguish keys the domain considers different. |
| Are keys enum constants? | EnumMap |
Constant order and prohibition of a null key. |
The table is a choice guide, rather than a performance measurement. A map does not correct a poorly designed key. If a BookCode class uses mutable fields for equals and hashCode, changing them after insertion can prevent finding the entry again. A record storing a normalized code is easier to use correctly. The order of TreeMap must also be consistent with the chosen meaning of identity: if two different codes compare as equal, a sorted map can treat them as the same key.
When the Key Is a Constant
If we record the number of loans present for each LoanStatus, keys belong to a finite set known to the compiler. EnumMap<LoanStatus, Integer> counts = new EnumMap<>(LoanStatus.class) creates an empty map of the right type. We can add an entry with put, remove it with remove and create a new map from an existing EnumMap. During iteration, keys follow the enum's declaration order, rather than the order in which we called put. A null key is forbidden; a null value is allowed, although for a count it is clearer to decide whether absence means zero or “not yet measured”.
Important note –
EnumMapIs Not an Enum. The enum defines possible keys; the map associates each key with a value that can change.EnumSetanswers “which states are present?”, andEnumMapanswers “which value corresponds to each state?”. This difference is the criterion for transferring the solution to a new problem. The Java 25 rules forEnumMapalso specify that its views have weakly consistent iterators: they do not throwConcurrentModificationException, but may or may not show a modification occurring during traversal. This is not a license to modify the map from several threads without coordination.
Stacks, Queues and Two Ends
A stack extracts the last inserted element first: LIFO. A queue extracts the oldest first: FIFO. Deque<E> supports operations from both ends and can represent both behaviors. ArrayDeque is an ordinary choice for a non-concurrent stack or queue. In the program we call push("first"), then push("second"); pop() prints second. This is the same behavior as the teaching stack, but with a generic library type. The old class Stack exists for compatibility; for new code it is not the choice to teach as the default stack.
Queue<E> expresses the queue. The methods add/remove and offer/poll differ in how they report certain failure or absence conditions; the caller must know the implementation's contract. PriorityQueue does not retain general FIFO: it extracts according to priority, defined by natural order or a comparator. The name “queue” is not enough to predict which element will come out.
The sequenced interfaces, available in Java 25, model collections with a defined encounter order and operations at the ends. SequencedCollection, SequencedSet and SequencedMap also allow a reversed() view. The SequencedCollection API specification clarifies the contract. Not every collection is sequenced: asking for the first element of a HashSet as if it had a promised order would be a modeling error.
Figure 17.5 separates the class Stack, which can be encountered in existing programs, from the contract Deque that we would use for a new stack.
Deque better expresses the structure choice. ArrayDeque is a possible non-concurrent implementation.The Library's Stack and the Book's Stack
Our teaching Stack had fixed capacity and methods chosen to understand invariants and errors. java.util.Stack<E> still exists: it extends Vector and provides push, pop, peek, empty and search. search(object) returns the distance from the top counting from one, rather than a list index; if the object does not appear, it returns -1. Knowing how to read a Stack is useful in existing code. For new code, the Deque documentation recommends the Deque contract, often implemented by ArrayDeque. push inserts at the front, pop removes from the front and peek observes the front without removing it: the same LIFO rule, expressed with a structure better suited to the need.
However, we must not confuse this stack of objects with the call stack shown by exceptions. A Deque<Book> is a container our program modifies; the call stack is part of a thread's execution context. The common name arises from LIFO order, but reading pop() in our collection does not remove a method from the call stack. The distinction avoids transferring a useful analogy beyond its scope.
Three Ways to Ask for a Queue's First Element
For a request queue, add(r) and offer(r) both attempt insertion. The former reports rejection due to capacity limits with an exception; the latter can return false. remove() and poll() extract the first element: on an empty queue, remove() throws an exception and poll() returns null. element() and peek() look at the first without removing it, with the same difference between exception and null when the queue is empty. The choice depends on how we want to represent the empty case in the caller's contract. There is no need to memorize six isolated names: we remember the three operations — insert, extract, observe — and the two reporting forms.
With ArrayDeque, null values are not inserted, so null returned by poll has an unambiguous meaning. A PriorityQueue answers a different question: “which request has the highest priority according to a criterion?”, rather than “which arrived first?”. If two requests have the same priority and arrival order matters, the comparator must also include a sequence number or another tie-breaker. Otherwise the program should not promise FIFO within the same priority level.
Modifiable, Unmodifiable and Immutable
List.of, Set.of and Map.of create unmodifiable collections. List.copyOf produces an unmodifiable list from another collection's values; in the program the copy of the three titles has size 3. These factories reject null; Set.of also rejects duplicate elements during creation. Unmodifiable means that we cannot add, replace or remove elements through that collection. It does not mean that contained objects are immutable: if a list contains a mutable object, it can still change.
Collections.unmodifiableList(list) instead creates an unmodifiable view of the received list: we cannot call add through the view, but modifications made to the original list can appear in the view. An unmodifiable copy and an unmodifiable view therefore answer different needs. When an API promises a snapshot, it must produce an appropriate copy and also consider element mutability, if relevant.
Arrays.asList lets us construct a list with a short expression. It is a useful shortcut, but precisely its brevity can hide an important difference. Passing an array obtains a fixed-size list linked to that array: set can replace an element and the change appears in the array, whereas add and remove cannot change the number of elements. This list is neither an ordinary resizable ArrayList nor an immutable copy. If the program must be able to add titles, we construct, for example, new ArrayList<>(Arrays.asList(data)); if it must retain an unmodifiable snapshot of the current references, we choose List.copyOf when values are non-null.
The ListViewsDemo.java program changes a single element and observes three paths. fixed modifies the array; copy retains the references present when it was constructed; view prevents modification through its own reference but continues to show the contents of the underlying list. We use immutable strings to isolate the structure's behavior. With mutable objects, even a list copy could show the mutated state of a shared object: copying the structure is not automatically a deep copy of its elements.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ListViewsDemo {
public static void main(String[] args) {
String[] data = {"Java", "Nets"};
List<String> fixed = Arrays.asList(data);
List<String> copy = List.copyOf(fixed);
List<String> view = Collections.unmodifiableList(fixed);
fixed.set(1, "API");
System.out.println("Array: " + Arrays.toString(data));
System.out.println("Copy: " + copy);
System.out.println("View: " + view);
try {
fixed.add("JVM");
} catch (UnsupportedOperationException error) {
System.out.println("Addition: " + error.getClass().getSimpleName());
}
}
}
The expected lines are Array: [Java, API], Copy: [Java, Nets], View: [Java, API] and Addition: UnsupportedOperationException. Before running it, try predicting them: the difference between copy and view becomes clear only if you follow when each observes data. Now change the requirement: a caller must receive existing titles but must not see future catalog additions. An unmodifiable view is not enough; a copy with the suitable contract is needed. If instead the caller must observe real-time updates without being able to make them, the view may be appropriate, provided code declares that it is not a snapshot and also defines the concurrent access discipline.
Iterating and Modifying with Judgment
An Iterator<E> allows a collection to be traversed with hasNext() and next(). Enhanced for uses this model when traversing an Iterable. If during iteration we want to remove the current element from a collection permitting it, we can use iterator.remove() according to the contract, rather than modifying the collection through another reference in the middle of the loop. Some iterators of common implementations detect unexpected structural modifications and throw ConcurrentModificationException; however, they are neither a synchronization mechanism nor an absolute guarantee of detection in every circumstance. In Chapter 20 we will use BlockingQueue and ArrayBlockingQueue to coordinate a producer and a consumer: the queue allows elements to be transferred between threads and callers to wait when it is full or empty.
The Name and the Problem. The Iterator pattern answers “how do I traverse elements without exposing the collection's internal structure?”. This is why, in pattern classification, it is a behavioral pattern, rather than creational: creating the iterator object is merely the way to start that behavior. The Java interface
Iterator<E>applies this idea with a precise contract;Iterable<T>is instead the contract of whoever can provide a new iterator. There is no need to memorize the label before understanding the problem–solution pair: a collection holds elements, and an iterator governs a traversal.
A small choice map summarizes the chapter's questions without replacing the explanation. If positions and duplicates are needed, start from List and often ArrayList; if uniqueness is needed, from Set; if searching by key is needed, from Map; if ends are needed, from Deque; if priority is needed, from PriorityQueue. Then decide the implementation by asking which guarantees of order, modification, nullability and cost are necessary. The cost of an operation also depends on size, key distribution, comparator and usage: a slogan such as “the map is always fast” is not enough.
The Library Catalog, Decision by Decision
Let us try choosing a collection without first looking at the class list. The catalog must find a book given its unique code. The question is a key search: Map<BookCode, Book> describes the contract well. If the code is a normalized string, the map can use String as key; if it has several parts, an immutable record can bring them together. The choice between HashMap, LinkedHashMap and TreeMap then depends on a second need: do we need no order, insertion order or code order? Choosing a TreeMap merely because “it sorts” adds a criterion the catalog may not require.
Now we want to show recent loans in recording order, even if two loans concern the same title. A List<Loan> preserves duplicates and position; a Set<Loan> could eliminate some according to equals, losing information. If loans grow without limit, a single in-memory list may not be the complete system model: the collection represents the portion loaded by the application, rather than replacing a persistent archive. Collection APIs do not decide by themselves how much history to retain or how to protect concurrent data.
To keep codes of books already displayed in a showcase, without duplicates and in the order they were added, LinkedHashSet<String> combines both properties. If order does not matter, HashSet expresses fewer guarantees and can suffice. If the showcase must always appear in alphabetical order, TreeSet or sorting at printing time can be considered according to how often data changes and how often it is read. The comparison criterion must remain consistent with the domain's intended meaning of duplicate.
For waiting loan requests, a FIFO queue is natural if arrival order decides who is served first. An ArrayDeque<Request> can express this behavior in a single thread. If requests arrive from several threads simultaneously, changing the variable's name is not enough: a concurrent structure and a contract on order and synchronization are needed, to be tackled in the dedicated chapter. If some requests have priority, PriorityQueue can represent the rule, but handling of ties and later arrivals must be defined.
This path shows why the collection type is more than a performance choice. It is part of the program's meaning: a list says repetitions matter, a set says they do not, a map identifies values through keys, and a deque exposes the ends. After expressing meaning, costs are measured if the real workload requires it. We do not choose LinkedList because “insertion is fast” without specifying where, how the point is reached and how many elements there are.
Good practice – Expose Only the Useful Guarantee. A method returning the catalog should not hand over the internal modifiable
HashMapif the caller must only read. It can return a view or copy with a declared contract. The choice between view and copy determines whether subsequent updates will become visible; it must be explained to API users.
Traversing Does Not Mean Owning
Let us try the Iterable and Iterator path with a list of three titles: Java, Nets, Java. Calling iterator() creates a cursor for that traversal. hasNext() asks whether an element remains, and next() returns it and advances the cursor. After three valid calls, another next() does not return null to signal the end: it throws NoSuchElementException. for (String title : titles) avoids manually writing the cursor, but traverses the same Iterable interface. It neither turns the list into an array nor produces a copy.
The iterator is not the owner of data: it is a disciplined way of traversing it. On a modifiable list, if we want to remove every empty title during traversal, we use iterator.remove() after reading the element, if the implementation permits that operation. ListIterator adds backward movement and operations such as add and set in the context of a list. These capabilities do not belong to a simple Iterator and are not guaranteed by every collection. For transformation of all values, building a new list can be clearer; for targeted removal, removeIf directly expresses the predicate. The choice depends on which result must be observed after the operation.
A Cursor Is Not a Copy of the Collection
Imagine marking the line you are reading in a catalog with a finger. The finger does not contain the catalog: it only indicates where you are. An Iterator<E> plays this role. hasNext() checks whether another read is possible, and next() returns the element and advances. This is why for (Book book : books) is convenient when reading every book, but not when a precise position or backward traversal is needed. Iterable is the contract of the object that can provide an iterator; Iterator is the cursor obtained for a single traversal. Calling iterator() again creates a new traversal, rather than rewinding the one already consumed.
The old interface Enumeration<E> still appears in some historical APIs and classes. It offers hasMoreElements() and nextElement(), without a method to remove the current element. If we encounter code returning it, we can read it as a forward cursor; asIterator() makes its remaining elements available through the Iterator interface. There is no reason to introduce Enumeration as the first choice for a new collection. This historical step is useful because old API names can appear in a real project, even though the teaching path uses enhanced for and Iterator.
A ListIterator<E> adds what the generic cursor lacks when the structure is a list: hasPrevious() and previous() allow going back, while nextIndex() and previousIndex() indicate the position that would be read in each direction. The cursor sits between elements. If a list contains A, B, C and we call listIterator(1), a call to next() returns B, while previous() returns A. At the beginning previousIndex() is -1; at the end nextIndex() is size(). These numbers are positions of a next read, rather than imaginary elements at the list's edges.
When the implementation permits modifications, ListIterator.add(e) inserts at the cursor point; set(e) replaces the last element returned by next() or previous(), if the sequence of calls permits. It is incorrect to describe set as “always replacing the element that will be read next”: its target depends on the read just performed. This precision is needed when transforming a list while traversing it. For an unmodifiable list, on the other hand, modification methods can throw UnsupportedOperationException even though they appear in the interface signature.
Modification During Traversal Is Not a Race Between Threads
An ArrayList can throw ConcurrentModificationException if we structurally change the list through another reference while traversing it. The exception helps discover incorrect use, but is not a promise to always detect it and does not make the list safe for several threads. If we want to remove elements during a single iteration, we use Iterator.remove() after next(), when supported by the implementation, or removeIf when the rule is a simple predicate. If another thread modifies the same structure, a concurrency policy defined for all participants is required; the mere presence of an iterator does not provide it.
The labels “fail-fast” and “fail-safe” encountered in some texts are shortcuts for different behaviors, rather than two standard interfaces to choose. An ArrayList iterator tries to report some unexpected structural modifications. EnumMap views have weakly consistent iterators: they can continue without an exception and observe or not observe intervening modifications. CopyOnWriteArrayList instead creates a traversal on a snapshot of the array at iteration time. These are different contracts; saying that all non-failing iterators work “on a clone” would be false. Before modifying a collection during traversal, we read its implementation's contract and decide which result we want to observe.
forEach and forEachRemaining: Where Does Work Start?
Iterable.forEach(action) traverses the elements provided by a new traversal and applies a Consumer to each. We can write titles.forEach(System.out::println) when the action is to print every title. An Iterator already obtained instead has forEachRemaining(action): it processes only elements remaining from the current point. If titles contains Java, Nets, API, a call to iterator.next() consumes Java; then iterator.forEachRemaining(System.out::println) prints Nets and API. It does not print Java again and does not modify titles. Enhanced for makes traversal control explicit in the program; forEach hands the action to the iterable object. In both cases the action's exceptions must be understood: a lambda does not make an operation that can fail harmless.
A map offers forEach((key, value) -> ...), in which the action is a BiConsumer because it receives two linked pieces of data. It is convenient for printing a pair. entrySet() remains preferable when we must pass entries to other methods or work with each Map.Entry as an object. If print order is part of the requirement, we choose a map promising it, such as LinkedHashMap or TreeMap; a lambda does not create an order the map did not have.
Algorithms, Views and the Cost of Choices
The Framework contains more than structures: it offers general operations such as sorting a list, finding a value or shuffling elements. Collections.sort(list) and list.sort(comparator) modify the order of the received list, if it supports modification; list.stream().sorted().toList() instead produces a new result list and leaves the source as it was. Calling both forms “sorting” without saying which object changes would make the continuation of the program difficult to predict. Binary search requires the sequence to already be sorted according to the same criterion used by the search: on a randomly ordered list, the method does not provide the desired result merely because its name contains search.
A subList is a view of part of the list, rather than necessarily an independent copy. If the caller retains the view and someone else structurally changes the source list, practical behavior can be surprising. When an independent snapshot is needed, constructing a new ArrayList<>(list.subList(start, end)) better expresses the intention. The reversed() of sequenced interfaces is also a reversed view: iterating it starts from the last position of the source collection, but does not promise a copy of data. The difference between view, copy and contained objects is one of the questions every API should resolve in its documentation.
What does a choice cost? ArrayList.get(i) uses the index to reach a position; LinkedList.get(i) requires traversing links. Inserting at the end of an ArrayList is normally inexpensive, but some insertions can require reallocating and copying the internal array. A HashMap generally offers efficient searching, but the contract is not a promise that every input, on every machine and with every hash function, costs the same time. The practical criterion remains choosing the structure from the meaning of data, then checking the cost of dominant operations and measuring if that cost really matters.
A Map Traversed Without Losing the Relationship
If the catalog uses Map<String, Book>, traversing only keySet() returns codes and traversing only values() returns books. When we must print the code together with the corresponding title, entrySet() exposes each pair as Map.Entry<String, Book>. We read getKey() and getValue() from the same entry, without searching again for the value for each key. This is an example where the view type communicates precisely what the loop traverses: not a generic list of objects, but associations between keys and values.
The unique-key rule must be observed in sequence. After put("J-01", bookA), the map contains an association; put("J-01", bookB) does not add a second entry with the same key, but replaces the value and returns the previous one according to the put contract. The number of entries remains one. If the problem requires several books for the same author, a simple Map<Author, Book> is not suitable: we can use Map<Author, List<Book>> or another model, declaring who creates and modifies the internal lists. Choosing a map is not enough to automatically solve a one-to-many relationship.
The views keySet, values and entrySet are linked to the map according to the implementation's contract. A view obtained from a modifiable map can reflect later updates; it is not a snapshot. Conversely, an explicit copy retains data observed at copying time, at least at the level of copied associations and references. If Book values are mutable, copying the map is not a deep copy of every book. This distinction returns to the difference already encountered with lists and prevents promising isolation when we have copied only the outer container.
Workshop: Choosing, Traversing and Retaining the Result
Let us put the pieces together without hiding steps. The library has a list of titles in which Java appears twice: repetition is legal because the list represents a sequence. It must compare two groups of titles for an exhibition, represent states fixed by an enum and retain an entry per code. Every need chooses a different contract. The complete program CollectionPathsDemo.java uses only small data, so we can predict every result before running it.
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
public class CollectionPathsDemo {
enum Status { AVAILABLE, ON_LOAN, RETURNED }
public static void main(String[] args) {
List<String> titles = new ArrayList<>(List.of("Java", "Nets", "Java"));
ListIterator<String> cursor = titles.listIterator(titles.size());
StringJoiner backwards = new StringJoiner(" | ");
while (cursor.hasPrevious()) {
backwards.add(cursor.previous());
}
System.out.println("List backwards: " + backwards);
Set<String> catalog = new LinkedHashSet<>(List.of("Java", "Nets"));
Set<String> exhibition = new LinkedHashSet<>(List.of("Nets", "API"));
Set<String> union = new LinkedHashSet<>(catalog);
union.addAll(exhibition);
Set<String> common = new LinkedHashSet<>(catalog);
common.retainAll(exhibition);
System.out.println("Union: " + union);
System.out.println("Common: " + common);
EnumSet<Status> visibleStatuses = EnumSet.of(
Status.AVAILABLE, Status.ON_LOAN);
EnumMap<Status, Integer> counts = new EnumMap<>(Status.class);
counts.put(Status.ON_LOAN, 2);
counts.put(Status.AVAILABLE, 5);
System.out.println("Statuses: " + visibleStatuses);
System.out.println("Counts: " + counts);
Iterator<String> iterator = titles.iterator();
iterator.next();
StringJoiner remaining = new StringJoiner(" | ");
iterator.forEachRemaining(remaining::add);
System.out.println("Remaining: " + remaining);
Map<String, String> books = new LinkedHashMap<>();
books.put("J-01", "Java");
books.put("R-02", "Nets");
books.put("R-02", "Nets, second edition");
books.forEach((code, title) ->
System.out.println(code + " -> " + title));
}
}
The first printed line is List backwards: Java | Nets | Java. The cursor starts from titles.size(), meaning after the last element, and previous() goes back. The fact that the two words Java are equal does not merge them: the list retains two positions. For union we copy catalog into a new LinkedHashSet and then call addAll(exhibition): we obtain [Java, Nets, API] without changing the two initial groups. For intersection we create another copy and call retainAll: [Nets] remains. If we removed the copy, the first operation would change the original set and the second question would start from different data.
EnumSet produces the statuses [AVAILABLE, ON_LOAN], while EnumMap prints {AVAILABLE=5, ON_LOAN=2} even though the program inserted ON_LOAN first. The map follows constant order, rather than put call order. After the iterator consumes Java, forEachRemaining gathers Nets | Java: the cursor does not restart from the beginning. Finally, LinkedHashMap prints two entries, J-01 -> Java and R-02 -> Nets, second edition. The second put with key R-02 updated an entry, rather than creating a third. Every output confirms a different property; the program is not a contest between implementations.
To Transfer the Solution. If the catalog had to show books alphabetically by title, merely changing
LinkedHashMaptoTreeMapwould not suffice: the map is indexed by code, so keys would be sorted. We would have to decide whether to construct a title-sorted view of entries or use another index. The reusable criterion is asking which information identifies the value and which information establishes presentation order.
When the forEach Action Can Fail
The simplest example is division: divisors.forEach(n -> System.out.println(10 / n)) stops with ArithmeticException if the list contains zero. If we put a try around the whole call, we catch the error but elements after zero are not processed. If the requirement is “try every divisor and report impossible ones”, the try goes inside the action, or we use an explicit for. The position of catch is not a style question: it decides whether processing continues. This is the same reasoning we built in Chapter 12 for exceptions, now applied to a repeated action.
Checked exceptions add a constraint. forEach receives a Consumer<T> whose method accept(T) does not declare throws IOException. A lambda directly calling read(name) if read declares throws IOException does not compile. We can handle the error inside the lambda; choose an ordinary for in whose calling method we propagate IOException; or adapt the action to an unchecked exception, making this choice explicit in the contract. The next complete program compares the last choice with element-by-element handling.
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.function.Consumer;
public class CollectionExceptionsDemo {
@FunctionalInterface
interface IOAction<T> {
void execute(T value) throws IOException;
}
static <T> Consumer<T> propagate(IOAction<T> action) {
return value -> {
try {
action.execute(value);
} catch (IOException error) {
throw new UncheckedIOException(error);
}
};
}
static void read(String name) throws IOException {
if (name.equals("missing")) {
throw new IOException("archive absent");
}
System.out.println("read: " + name);
}
public static void main(String[] args) {
List<String> names = List.of("catalog", "missing", "history");
try {
names.forEach(propagate(CollectionExceptionsDemo::read));
} catch (UncheckedIOException error) {
System.out.println("interrupted: " + error.getCause().getMessage());
}
for (String name : names) {
try {
read(name);
} catch (IOException error) {
System.out.println("skipped: " + name);
}
}
}
}
The first traversal prints read: catalog, then encounters missing and the wrapper transforms the IOException into UncheckedIOException, retaining it as the cause. The outer catch prints interrupted: archive absent; history is not read. The second traversal uses a for: it prints read: catalog again, then skipped: missing and finally read: history. We changed the program's policy, rather than merely loop syntax. The class UncheckedIOException still communicates that the failure originates in I/O; a generic RuntimeException would lose this specific information, though it could retain the cause.
The generic method propagate is an adapter: it receives an IOAction<T> capable of declaring IOException and returns a Consumer<T> accepted by forEach. It is not a shortcut to automatically apply to every checked exception. If the caller must know which file failed and continue with the others, the second path or a structured result is clearer. If the operation must stop at the first error, the adapter makes the error visible outside and maintains the cause. The brick to reuse is the question “what must happen to subsequent elements when one fails?”; the answer decides where to catch the exception and which API to use.
To Verify
Compile CollectionsDemo.java, CollectionPathsDemo.java and CollectionExceptionsDemo.java with javac --release 25 -Xlint:all -d build followed by the three filenames; then run each class. Before execution, predict why the list retains two Java values, the set only one, and the map updates R-02 without increasing size. Remove thenComparing from the TreeSet comparator: how many titles remain and which information was lost? Try calling add on the list produced by List.copyOf and explain the error. Finally change the workshop requirement: after a missing file, processing must continue with subsequent ones. Indicate which of the two paths in CollectionExceptionsDemo satisfies the requirement and why. If you can choose the structure and error handling for this variant, you have taken the brick beyond the initial example.