Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
The Java Collections Framework for the OCP 21 exam: List, Set, Queue, Deque and Map, generics with the diamond operator and var, and the Collection methods add, remove, size, isEmpty, clear, contains, removeIf, forEach, iterators, equals and unboxing pitfalls.
kvi5hnuCode Sprout team member7 min readOn this page
A collection is an object that holds a group of other objects. The Java Collections Framework, in the java.util package, provides the interfaces and classes for storing and processing such groups. Chapter 9 covers the parts the exam needs: the main collection types, sorting, the new Java 21 sequenced collections, and writing your own generic code.
The main interfaces
| Interface | What it models | Duplicates? | Order |
|---|---|---|---|
List | an indexed sequence | allowed | by position (index from 0) |
Set | a group of unique elements | not allowed | depends on the implementation |
Queue | elements waiting to be processed | allowed | processing order, usually FIFO |
Deque | a queue usable at both ends (extends Queue) | allowed | front and back |
Map | key/value pairs | no duplicate keys | depends on the implementation |
List, Set and Queue extend Collection. Map doesn't. A map is part of the framework, and it's a collection in the everyday sense, but its operations work on key/value pairs, so it has its own interface with different methods.
Java 21 added three sequenced interfaces, SequencedCollection, SequencedSet and SequencedMap, for types that have a well-defined first and last element. Article 57 covers them.

Generics in one minute
Collections are generic. The type in angle brackets says what they hold:
List<Integer> scores = new ArrayList<Integer>();
scores.add(42);
int first = scores.get(0); // no cast needed
scores.add("high"); // DOES NOT COMPILE: String isn't an Integer
Without generics (a raw type, as in List scores = new ArrayList();), anything can be added and every get needs a cast. Raw types still compile for backward compatibility, but with warnings. Article 58 covers writing your own generic code.
The diamond operator and var
Repeating the type arguments on both sides is redundant. The diamond operator <> lets the compiler infer them on the right:
List<Integer> scores = new ArrayList<>();
Map<String, List<Integer>> byPlayer = new HashMap<>();
The diamond can only appear in a new expression. It can't be used as a declared type:
List<> scores = new ArrayList<Integer>(); // DOES NOT COMPILE
void record(List<> data) { } // DOES NOT COMPILE
var infers in the opposite direction, from the right side. So the type arguments must be written on the right:
var scores = new ArrayList<Integer>(); // ArrayList<Integer>
var stock = new HashMap<>(); // compiles: HashMap<Object, Object>
Combining var and <> leaves the compiler nothing to infer from, so it falls back to Object. That compiles, but String s = stock.get("k"); then fails, because get returns Object.
Common Collection methods
These methods are declared in Collection, so they work on every list, set and queue. The examples use ArrayList and TreeSet, but the behavior shown is the Collection contract.
| Method | Returns | Meaning |
|---|---|---|
add(E e) | boolean | adds e, and returns whether the collection changed |
remove(Object o) | boolean | removes one matching element, and returns whether one was found |
isEmpty() / size() | boolean / int | number of elements |
clear() | void | removes everything |
contains(Object o) | boolean | whether an equal element is present (uses equals) |
removeIf(Predicate<? super E>) | boolean | removes all matches, and returns whether anything was removed |
forEach(Consumer<? super E>) | void | runs an action for each element (inherited from Iterable) |
addAll, removeAll, retainAll, containsAll | boolean | bulk versions that take another collection |
toArray() / toArray(T[]) | array | copies the elements into an array (article 53) |
add and remove
Collection<String> visits = new ArrayList<>();
visits.add("Kai"); // true
visits.add("Kai"); // true: lists accept duplicates
Collection<String> guests = new HashSet<>();
guests.add("Kai"); // true
guests.add("Kai"); // false: already present, set unchanged
remove deletes only the first matching element and returns false when nothing matches:
Collection<String> birds = new ArrayList<>(List.of("owl", "owl"));
birds.remove("crow"); // false
birds.remove("owl"); // true -> [owl]
Note that remove and contains take an Object, not an E. birds.remove(42) compiles and simply returns false.
removeIf and forEach
Both take functional interfaces from chapter 8:
Collection<String> names = new ArrayList<>(List.of("Ava", "", "Zed", ""));
names.removeIf(String::isEmpty); // Predicate -> [Ava, Zed]
names.forEach(n -> System.out.println(n)); // Consumer
names.forEach(System.out::println); // same thing
Iterating
Besides forEach, you can use an enhanced for loop, or an explicit Iterator:
Iterator<String> it = names.iterator();
while (it.hasNext()) { // is there another element?
String n = it.next(); // move to it and return it
if (n.startsWith("Z")) it.remove(); // removes the element just returned
}
hasNext() only looks ahead. next() actually advances, and it throws NoSuchElementException if nothing is left.
Never add to or remove from a collection directly while an enhanced for loop (or another iterator) is walking over it. Most JDK collections detect that and throw ConcurrentModificationException on the next step. Use iterator.remove() or removeIf instead.
equals
Collections implement equals according to their kind:
List.of(1, 2).equals(List.of(2, 1)); // false: lists compare in order
Set.of(1, 2).equals(Set.of(2, 1)); // true: sets ignore order
List.of(1, 2).equals(Set.of(1, 2)); // false: a list never equals a set
List.of(1, 2).equals(new LinkedList<>(List.of(1, 2))); // true: any List with the same elements in order
Unboxing null
Collections of wrapper types can hold null, and that sets a trap:
var heights = new ArrayList<Integer>();
heights.add(null); // legal
int h = heights.get(0); // NullPointerException: unboxing null
Assigning the Integer to an int calls intValue() behind the scenes, and calling a method on null throws.
Immutable factory collections
List.of(...), Set.of(...) and Map.of(...) create unmodifiable collections. The next articles cover them in detail, but two rules apply everywhere:
- Every modifying method (
add,remove,clear,removeIf, …) throwsUnsupportedOperationException. This happens even when the call wouldn't change anything, such as removing an element that isn't there. - They reject
nullelements with aNullPointerException, even in queries such ascontains(null).Set.ofalso rejects duplicates with anIllegalArgumentException.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Java 21 added sequenced collections (article 57). Apart from
copyOf(Java 10) andCollection.toArray(IntFunction)(Java 11), they're the only change to the core collection interfaces since the Java 9 factory methods.
Exam traps from this article
A complete example
The same names go into an ArrayList and a TreeSet, both used only through Collection references. The program shows the return values of add, remove and removeIf, forEach, removal through an Iterator, equals across collection types, and an unmodifiable list.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Solution {
static void report(String label, Collection<String> c) {
System.out.println(label + ": size=" + c.size() + " empty=" + c.isEmpty() + " " + c);
}
public static void main(String[] args) {
// Program to the interface: both variables are just Collection<String>
Collection<String> visits = new ArrayList<>(); // allows duplicates
Collection<String> guests = new TreeSet<>(); // no duplicates, sorted for stable output
for (String name : List.of("Kai", "Mo", "Kai", "Ava", "Mo", "Zed")) {
boolean v = visits.add(name);
boolean g = guests.add(name);
System.out.println("add " + name + ": list " + v + ", set " + g);
}
report("visits", visits);
report("guests", guests);
System.out.println("remove Mo once: " + visits.remove("Mo") + " -> " + visits);
System.out.println("remove Lu: " + visits.remove("Lu"));
System.out.println("contains Ava? " + guests.contains("Ava"));
// removeIf takes a Predicate and reports whether anything changed
System.out.println("removeIf starts with Z: " + guests.removeIf(s -> s.startsWith("Z")) + " -> " + guests);
// forEach takes a Consumer
System.out.print("forEach:");
visits.forEach(s -> System.out.print(" " + s));
System.out.println();
// Iterator: the safe way to remove while looping
Iterator<String> it = visits.iterator();
while (it.hasNext()) {
if (it.next().equals("Kai")) it.remove();
}
System.out.println("after iterator removal: " + visits);
// equals: lists care about order, sets don't, and a list never equals a set
System.out.println("List.of(1,2).equals(List.of(2,1)) = " + List.of(1, 2).equals(List.of(2, 1)));
System.out.println("Set.of(1,2).equals(Set.of(2,1)) = " + Set.of(1, 2).equals(Set.of(2, 1)));
System.out.println("new HashSet(guests).equals(guests) = " + new HashSet<>(guests).equals(guests));
// Immutable collections reject changes at run time
Collection<String> fixed = List.of("A", "B");
try {
fixed.add("C");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is unmodifiable: " + e.getClass().getSimpleName());
}
guests.clear();
report("guests after clear", guests);
}
}
Output:
add Kai: list true, set true
add Mo: list true, set true
add Kai: list true, set false
add Ava: list true, set true
add Mo: list true, set false
add Zed: list true, set true
visits: size=6 empty=false [Kai, Mo, Kai, Ava, Mo, Zed]
guests: size=4 empty=false [Ava, Kai, Mo, Zed]
remove Mo once: true -> [Kai, Kai, Ava, Mo, Zed]
remove Lu: false
contains Ava? true
removeIf starts with Z: true -> [Ava, Kai, Mo]
forEach: Kai Kai Ava Mo Zed
after iterator removal: [Ava, Mo, Zed]
List.of(1,2).equals(List.of(2,1)) = false
Set.of(1,2).equals(Set.of(2,1)) = true
new HashSet(guests).equals(guests) = true
List.of is unmodifiable: UnsupportedOperationException
guests after clear: size=0 empty=true []
Points to notice:
- The list's
addalways returnstrue. The set returnsfalsefor the secondKaiandMo. TreeSetkeeps its elements sorted, which makes the output predictable. AHashSetwould print them in an unspecified order.visits.remove("Mo")removes only the firstMo.- The iterator removes both
Kaientries safely while looping. new HashSet<>(guests).equals(guests)istrueacross implementations, because both are sets with the same elements.
Common questions
Should variables be declared as List/Collection or as ArrayList?
Prefer the interface (List<String> names = new ArrayList<>();). The code then depends only on the behavior it needs, and you can swap implementations later.
Is the order of a HashSet really random?
It's unspecified. It depends on hash codes and capacity, and it can change between runs or JDK versions, so never rely on it. Use LinkedHashSet or TreeSet when order matters.
Why does contains take Object instead of E?
For historical compatibility. It means a call with an unrelated type compiles and just returns false, so don't rely on the compiler to catch that mistake.
Summary
List(ordered, duplicates allowed),Set(no duplicates),Queue/Deque(processing order) extendCollection.Mapstores key/value pairs and doesn't extend it.- Generics give type safety.
<>infers type arguments from the declared type, andvarinfers from the right side. Both together giveObject. add,remove,removeIf,addAlland friends return whether the collection changed.containsandremoveuseequals.- Iterate with
forEach, an enhancedfor, or anIterator. UseIterator.removeorremoveIfto remove while iterating. - List equality depends on order, set equality doesn't, and lists never equal sets. Unboxing a
nullelement throwsNullPointerException.
Practice quiz
Test yourself with the collection basics quiz: 10 exam-style questions with explanations.
Previous: Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
Next: Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
Related reading
- Java Variable Scope and Garbage Collection (OCP 21)
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
- Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
- Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.