The Java Collections Framework: Interfaces, Implementations and Iterators
Start the Java Collections Framework: why interfaces are separate from implementations, the Collection and Iterable interfaces, how iterators work between elements, next, hasNext and remove, forEach, bulk operations, and building your own collection with AbstractCollection.
kvi5hnuCode Sprout team member13 min readOn this page
The data structures you choose make a big difference, both to how naturally you can express your code and to how fast it runs. Do you need to search quickly through millions of sorted items? Insert and remove elements in the middle of a sequence? Associate keys with values? The Java Collections Framework provides ready-made, well-tested answers to all of these questions.
A university data structures course spends a semester on the theory. This part of the course takes a practical approach instead: how the framework is designed, how to use its interfaces and classes, and which one to choose when.
A short history
The first release of Java offered only a few classes for the most useful data structures: Vector, Stack, Hashtable, BitSet and the Enumeration interface for visiting elements. That was a sensible start, because designing a comprehensive collections library takes time and skill.
Java 1.2 introduced a full framework. Its designers faced conflicting goals. They wanted the library small and easy to learn, without the complexity of the C++ Standard Template Library (STL), but with the STL's benefit of generic algorithms. They also wanted the legacy classes to fit in. As every collections designer does, they made some hard choices and some idiosyncratic decisions. This article covers the basic design. Later articles explain the reasoning behind its more debated features.
Separating interfaces and implementations
Like most modern data structure libraries, the Java Collections Framework separates interfaces from implementations. Look at a familiar structure, the queue.
A queue interface says that you can add elements at the tail, remove them from the head, and find out how many elements there are. You use a queue to collect objects and retrieve them "first in, first out" (FIFO). A minimal queue interface could look like this:
public interface Queue<E> { // a simplified form of the interface in the standard library
void add(E e);
E remove();
int size();
}
The interface says nothing about how the queue is implemented. There are two common implementations: a circular array and a linked list.

Each implementation is a class that implements Queue. In the Java API, they are called ArrayDeque and LinkedList:
public class ArrayDeque<E> implements Queue<E> { // not the actual implementation
private int first;
private int last;
private E[] elements;
public ArrayDeque(int numElements) { . . . }
public void add(E e) { . . . }
public E remove() { . . . }
public int size() { . . . }
. . .
}
public class LinkedList<E> implements Queue<E> { // not the actual implementation
private Node<E> first;
private Node<E> last;
public LinkedList() { . . . }
public void add(E e) { . . . }
public E remove() { . . . }
public int size() { . . . }
. . .
}
Once you've constructed a queue, you don't need to know which implementation you have. So use the concrete class only when constructing the collection, and use the interface type for the variable:
Queue<Customer> expressLane = new ArrayDeque<>(100);
expressLane.add(new Customer("Omar"));
If you change your mind, you change one place, the constructor call:
Queue<Customer> expressLane = new LinkedList<>();
expressLane.add(new Customer("Omar"));
There's another benefit. ArrayDeque and LinkedList both have methods that have nothing to do with queues. If you accidentally call one of them, the compiler reports an error, because those methods don't exist on a Queue variable.
Why choose one implementation over another? The interface says nothing about efficiency. A circular array uses memory more efficiently, but it has a fixed capacity and must be reallocated when it fills up. In practice, measurements show that ArrayDeque usually outperforms LinkedList, partly because it creates far less work for the garbage collector. When ArrayDeque arrived in Java 6, programmers who had used the Queue interface could switch from LinkedList by changing a single line.
The Collection interface
The fundamental interface of the framework is Collection. It has two fundamental methods:
public interface Collection<E> {
boolean add(E element);
Iterator<E> iterator();
. . .
}
add adds an element and returns true if this actually changed the collection, false if not. For example, adding an object that a set already contains has no effect, because sets reject duplicates.
iterator returns an object implementing the Iterator interface, which visits the elements one by one.
Iterators
The Iterator interface has four methods:
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove();
default void forEachRemaining(Consumer<? super E> action);
}
Calling next repeatedly visits the elements one by one. At the end of the collection, next throws a NoSuchElementException, so call hasNext first. It returns true if there's at least one more element. To inspect all elements, get an iterator and call next while hasNext returns true:
Collection<String> coll = . . .;
Iterator<String> iter = coll.iterator();
while (iter.hasNext()) {
String element = iter.next();
do something with element
}
The "for each" loop says the same thing more concisely:
for (String element : coll) {
do something with element
}
The compiler simply translates it into a loop with an iterator. The "for each" loop works with any object that implements Iterable, an interface with one abstract method:
public interface Iterable<E> {
Iterator<E> iterator();
. . .
}
Collection extends Iterable, so every collection in the framework works with "for each". You can make your own classes iterable too.
Instead of a loop, you can also pass a lambda to Collection.forEach or Iterator.forEachRemaining. The lambda is called for every element, or for every element the iterator has not yet visited:
coll.forEach(element -> do something with element);
iter.forEachRemaining(element -> do something with element);
Iteration order
The order in which elements are visited depends on the collection. An ArrayList iterator starts at index 0 and moves up one index at a time. A HashSet gives you its elements in an essentially random order. You're guaranteed to see every element exactly once, but you can't assume anything about the order. Usually that doesn't matter: totals and counts come out the same in any order. When it does matter, pick an ordered collection such as ArrayList, LinkedHashSet or TreeSet.
Iterators are between elements
Java iterators work differently from iterators in some other libraries. In the C++ STL, iterators are modeled after array indexes. Given such an iterator, you can look up the element at that position, just as you look up a[i] with an index i, and, independently, you can advance the iterator, like i++, without a lookup.
Java iterators don't work like that. Lookup and advancing are tightly coupled. The only way to look up an element is to call next, and that advances the position. Think of a Java iterator as sitting between elements. When you call next, the iterator jumps over the next element and returns a reference to the element it just passed.

Another useful analogy: Iterator.next is like InputStream.read. Reading a byte "consumes" it, and the next read returns the following byte. Repeated next calls likewise consume the whole collection.
Removing elements
Iterator.remove removes the element returned by the last call to next. That often makes sense, because you need to look at an element before deciding to remove it. But even to remove an element at a known position, you must skip past it first. Here's how to remove the first element of a collection of strings:
Iterator<String> iter = coll.iterator();
iter.next(); // skip over the first element
iter.remove(); // now remove it
There's a dependency between next and remove. Calling remove without a preceding next is illegal and throws an IllegalStateException. To remove two adjacent elements, you can't just write
iter.remove();
iter.remove(); // ERROR
You must first jump over the element to remove:
iter.remove();
iter.next();
iter.remove(); // OK
remove is optional. Iterators of unmodifiable collections throw UnsupportedOperationException, which is the default implementation of the method.
Generic utility methods
Because Collection and Iterator are generic, you can write utility methods that work with any collection. This generic method tests whether a collection contains an element:
public static <E> boolean contains(Collection<E> c, Object obj) {
for (E element : c)
if (element.equals(obj))
return true;
return false;
}
The framework designers decided that some of these utilities are so useful that every collection should offer them, so users don't have to keep reinventing the wheel. contains is one of them. In fact, Collection<E> declares many methods that all implementing classes must provide:
int size()
boolean isEmpty()
boolean contains(Object obj)
boolean containsAll(Collection<?> c)
boolean add(E obj)
boolean addAll(Collection<? extends E> from)
boolean remove(Object obj)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
void clear()
Object[] toArray()
<T> T[] toArray(T[] a)
Collection also redeclares equals and hashCode from Object. There's no technical need. It just gives the documentation a place to describe collection-specific behavior. Set and List define exactly what equals means for them. Other collections may inherit Object.equals, or override it, together with hashCode.
AbstractCollection
It would be a bother if every class implementing Collection had to write all these routine methods. To make life easier for implementors, the framework provides AbstractCollection. It leaves the fundamental methods size and iterator abstract and implements the routine methods in terms of them:
public abstract class AbstractCollection<E> implements Collection<E> {
. . .
public abstract Iterator<E> iterator();
public abstract int size();
public boolean isEmpty() { return size() == 0; }
public boolean contains(Object obj) {
for (E element : this) // calls iterator()
if (Objects.equals(element, obj))
return true;
return false;
}
. . .
}
A concrete collection can extend AbstractCollection and supply only iterator and size, plus add if it is mutable. Everything else, including contains, toArray and toString, is inherited. If the subclass has a more efficient way to implement, say, contains, it's free to override it. The demo's IntRange represents a range of integers without storing them and gets a complete collection API for a few lines of code.
This approach is a bit dated. Today, these would be default methods of the Collection interface, but default methods didn't exist when the framework was designed. Several default methods have since been added: three that deal with streams (stream, parallelStream, spliterator), toArray(IntFunction), and the very useful
default boolean removeIf(Predicate<? super E> filter)
for removing all elements that fulfill a condition.
A complete example
import java.nio.file.Path;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. program to the interface; pick the implementation in one place
Queue<String> expressLane = new ArrayDeque<>(10);
expressLane.add("Omar");
expressLane.add("Sally");
System.out.println("ArrayDeque serves " + expressLane.remove() + ", size " + expressLane.size());
expressLane = new LinkedList<>(); // only the constructor call changes
expressLane.add("Omar");
expressLane.add("Sally");
System.out.println("LinkedList serves " + expressLane.remove() + ", size " + expressLane.size());
// 2. add reports whether the collection changed
Collection<String> tags = new TreeSet<>();
System.out.println("add java: " + tags.add("java") + ", add java again: " + tags.add("java"));
// 3. four ways to visit every element
Collection<String> coll = new ArrayList<>(List.of("Ava", "Ben", "Cleo", "Dev"));
Iterator<String> iter = coll.iterator();
var sb = new StringBuilder("iterator:");
while (iter.hasNext()) sb.append(' ').append(iter.next());
System.out.println(sb);
sb = new StringBuilder("for each:");
for (String element : coll) sb.append(' ').append(element);
System.out.println(sb);
var collected = new StringJoiner(" ", "forEach: ", "");
coll.forEach(collected::add);
System.out.println(collected);
Iterator<String> rest = coll.iterator();
rest.next(); // skip Ava
var remaining = new StringJoiner(" ", "forEachRemaining after one next(): ", "");
rest.forEachRemaining(remaining::add);
System.out.println(remaining);
try {
rest.next();
} catch (NoSuchElementException e) {
System.out.println("next() past the end: NoSuchElementException");
}
// 4. Iterator.remove removes the element returned by the last next()
Iterator<String> it = coll.iterator();
it.next(); // skip over Ava
it.remove(); // now remove it
try {
it.remove(); // a second remove without next()
} catch (IllegalStateException e) {
System.out.println("remove twice: IllegalStateException");
}
it.next();
it.remove(); // removes Ben
System.out.println("after removals: " + coll);
// 5. bulk operations of the Collection interface
Collection<Integer> a = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
Collection<Integer> b = List.of(4, 5, 6, 7);
System.out.println("containsAll " + a.containsAll(List.of(1, 2)) + ", contains 9 " + a.contains(9));
var union = new TreeSet<>(a);
union.addAll(b);
var intersection = new ArrayList<>(a);
intersection.retainAll(b);
var difference = new ArrayList<>(a);
difference.removeAll(b);
System.out.println("union " + union + ", intersection " + intersection + ", difference " + difference);
a.removeIf(n -> n % 2 == 0);
Integer[] odd = a.toArray(Integer[]::new);
System.out.println("removeIf even -> " + Arrays.toString(odd));
// 6. contains/remove take Object: this mistake compiles
Collection<Path> paths = new ArrayList<>(List.of(Path.of("/tmp"), Path.of("/home")));
boolean removed = paths.remove("/tmp"); // a String, not a Path!
System.out.println("remove(\"/tmp\") removed something? " + removed + " " + paths.size());
// 7. a generic utility method works on any collection
System.out.println("contains: " + contains(List.of(3, 1, 4), 4) + " " + contains(Set.of("x"), "y"));
// 8. AbstractCollection: supply iterator() and size(), inherit the rest
var range = new IntRange(3, 8);
System.out.println(range + " size " + range.size() + ", contains 5? " + range.contains(5)
+ ", contains 9? " + range.contains(9));
int sum = 0;
for (int n : range) sum += n; // for each works because Collection extends Iterable
System.out.println("sum " + sum);
}
public static <E> boolean contains(Collection<E> c, Object obj) {
for (E element : c)
if (element.equals(obj)) return true;
return false;
}
}
/** The integers from start (inclusive) to end (exclusive), computed on the fly. */
class IntRange extends AbstractCollection<Integer> {
private final int start;
private final int end;
IntRange(int start, int end) { this.start = start; this.end = end; }
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int next = start;
@Override public boolean hasNext() { return next < end; }
@Override public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return next++;
}
};
}
@Override
public int size() { return Math.max(0, end - start); }
}
ArrayDeque serves Omar, size 1
LinkedList serves Omar, size 1
add java: true, add java again: false
iterator: Ava Ben Cleo Dev
for each: Ava Ben Cleo Dev
forEach: Ava Ben Cleo Dev
forEachRemaining after one next(): Ben Cleo Dev
next() past the end: NoSuchElementException
remove twice: IllegalStateException
after removals: [Cleo, Dev]
containsAll true, contains 9 false
union [1, 2, 3, 4, 5, 6, 7], intersection [4, 5, 6], difference [1, 2, 3]
removeIf even -> [1, 3, 5]
remove("/tmp") removed something? false 2
contains: true false
[3, 4, 5, 6, 7] size 5, contains 5? true, contains 9? false
sum 25
Common questions
Should I declare a variable as ArrayList<String> or List<String>?
Use the interface, List<String>, unless you need a method that only the class has, such as ensureCapacity. Your code stays independent of the implementation, and you can switch to another one by changing the new expression.
Why does removing elements in a for-each loop throw ConcurrentModificationException?
The loop uses a hidden iterator, and list.remove(x) changes the list behind its back. On the next step, the iterator detects the change and throws. Use iterator.remove() inside an explicit iterator loop, or simply list.removeIf(x -> condition).
Is forEach with a lambda faster than a for-each loop?
Not in any way that matters for normal code. Choose whichever reads better. A for-each loop can use break, return and checked exceptions, which a lambda can't.
Why does contains take an Object and not an E?
The method was defined before generics, and changing it would have broken existing code. As a side effect, names.contains(42) on a List<String> compiles and simply returns false. IDE inspections and tools such as Error Prone flag such calls.
Are Enumeration, Vector and Hashtable still useful?
They're legacy classes. Some old APIs still return Enumeration, and Enumeration.asIterator() (Java 9) adapts it. In new code, use Iterator, ArrayList and HashMap, or the concurrent collections when threads share data.
API reference
java.util.Collection<E>
| Method | Description |
|---|---|
Iterator<E> iterator() | An iterator for visiting the elements |
int size() | The number of elements |
boolean isEmpty() | true if there are no elements |
boolean contains(Object obj) | true if an element equal to obj is present |
boolean containsAll(Collection<?> other) | true if all elements of other are present |
boolean add(E element) | Adds an element. Returns true if the collection changed |
boolean addAll(Collection<? extends E> other) | Adds all elements of other. Returns true if the collection changed |
boolean remove(Object obj) | Removes an element equal to obj. Returns true if one was removed |
boolean removeAll(Collection<?> other) | Removes all elements found in other. Returns true if the collection changed |
default boolean removeIf(Predicate<? super E> filter) | Removes all elements matching the filter (Java 8). Returns true if the collection changed |
void clear() | Removes all elements |
boolean retainAll(Collection<?> other) | Removes all elements not found in other. Returns true if the collection changed |
Object[] toArray() | An array of the elements |
<T> T[] toArray(T[] arrayToFill) | Fills arrayToFill if large enough, otherwise a new array of the same type |
default <T> T[] toArray(IntFunction<T[]> generator) | An array built with the generator, typically T[]::new (Java 11) |
java.util.Iterator<E>
| Method | Description |
|---|---|
boolean hasNext() | true if there is another element to visit |
E next() | Returns the next element. Throws NoSuchElementException at the end |
default void remove() | Removes the last visited element. Must immediately follow next, otherwise IllegalStateException. Optional: the default throws UnsupportedOperationException |
default void forEachRemaining(Consumer<? super E> action) | Passes each remaining element to the action (Java 8) |
Summary
- The framework separates interfaces (what a collection does) from implementations (how). Use interface types for variables and parameters, and concrete classes only with
new. Collectionhasadd(returns whether the collection changed) anditerator, plus many utility methods.AbstractCollectionimplements most of them for you.IteratorhashasNext,next,removeandforEachRemaining. "for each" works with anyIterable.- Java iterators sit between elements:
nextboth advances and returns.removedeletes the element last returned bynext, once. - Iteration order depends on the implementation: index order for lists, unspecified for
HashSet. containsandremoveaccept anyObject, so wrong-typed calls compile and silently do nothing.- Use
removeIforIterator.removeto remove elements during iteration. Never modify the collection directly inside a "for each" loop.
Practice Questions
Why declare Queue<Task> q = new ArrayDeque<>(); instead of ArrayDeque<Task> q = new ArrayDeque<>();?
With the interface type, switching implementations means changing just the constructor call, and the compiler prevents accidental use of methods that aren't part of the queue abstraction.
What does Set.add return when the element is already present?
false: the set rejected the duplicate and didn't change.
A list contains A, B, C. What does this do: it = list.iterator(); it.next(); it.next(); it.remove();?
It removes B, the element returned by the most recent next call. The list becomes [A, C].
Why does calling iter.remove() twice in a row throw an exception?
remove deletes the element returned by the last next. After the first remove, there's no such element until next is called again, so the second remove throws IllegalStateException.
What is the minimum you must implement when extending AbstractCollection for an unmodifiable collection?
iterator() and size(). All other Collection methods are inherited. For a modifiable collection, also implement add, and support remove in the iterator.
Collection<Integer> nums = ...; nums.remove("5"); — does this compile, and what happens?
It compiles, because remove takes an Object, but it never removes anything: no Integer equals the string "5". It returns false.
Previous: Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
Next: Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
Related reading
- Java ArrayList: Generic Array Lists Explained
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Restrictions and Limitations: What You Can't Do with Type Parameters

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.