Collections & Lists
The Collections framework, ArrayList vs LinkedList, Iterator, removeIf, immutable lists and queues.
Arrays have a fixed size. Real programs need collections that grow and shrink: a shopping cart, a to-do list, search results. The Collections framework (java.util) provides ready-made, well-tested data structures. This lesson gives an overview of the framework and then focuses on the one you will use most: List.
The Collections framework at a glance#
- Interfaces (
List,Set,Map) define behaviour. - Implementations (
ArrayList,HashSet...) choose a data structure with different performance trade-offs. - Utility classes:
CollectionsandArrayshold static helpers (sort, shuffle, unmodifiable views...).
Program to the interface: List<String> names = new ArrayList<>();
ArrayList basics#
A List keeps elements in insertion order, allows duplicates, and gives index access from 0 to size() - 1. get with a bad index throws IndexOutOfBoundsException.
Looping over a list#
Iterator: the engine behind for-each#
Every collection provides an Iterator, an object that walks through elements one by one with hasNext() and next(). The for-each loop is just syntax that uses one. You need the iterator explicitly when removing during iteration:
Collections' iterators are fail-fast: they detect structural changes made outside the iterator and throw ConcurrentModificationException rather than misbehave. Prefer removeIf in modern code.
ListIterator goes further: it can move backwards (hasPrevious, previous) and replace (set) or insert (add) elements while iterating.
Sorting and other utilities#
Sorting is stable: equal elements (like bob and Zed, both length 3) keep their relative order. Comparators get their own lesson soon.
Java 21: sequenced collections#
Java 21 added the SequencedCollection interface, giving lists (and other ordered collections) uniform first/last methods:
No more list.get(list.size() - 1).
Immutable lists#
Returning unmodifiable lists from your methods prevents callers from corrupting your object's state.
ArrayList vs LinkedList#
ArrayListstores elements in a resizable array. When full, it allocates a bigger one (about 1.5×) and copies.LinkedListstores a chain of nodes, each pointing to the next and previous node.
In practice, use ArrayList by default. Its contiguous memory makes it faster than LinkedList for almost everything, even many middle insertions. If you need fast operations at both ends, use ArrayDeque, not LinkedList.
Tip: if you know roughly how many elements you will add,
new ArrayList<>(10_000)avoids repeated resizing.
Queues and deques#
A Queue hands elements out in a processing order; a Deque ("deck") works at both ends, so it can be a queue or a stack:
offer/poll/peekreturnfalse/nullon failure;add/remove/elementthrow exceptions instead.- Use
ArrayDequefor stacks (instead of the legacyStackclass) and FIFO queues. PriorityQueuealways gives the smallest element first (or by aComparatoryou supply). It is great for schedulers and algorithms like Dijkstra's.
Big-O in one minute#
Big-O describes how the cost of an operation grows with the number of elements n:
- O(1) constant: the same speed for 10 or 10 million elements.
- O(log n): grows very slowly (tree lookups, binary search).
- O(n) linear: twice the elements, twice the time (scanning a list with
contains).
Calling list.contains(x) inside a loop over another list is O(n²) and becomes slow with large data. A HashSet (next lesson) makes contains O(1).
Common mistakes#
- Removing elements inside a for-each loop.
- Confusing
remove(int index)withremove(Object o)on aList<Integer>. - Modifying a
List.oforArrays.asListlist. - Choosing
LinkedList"because inserts are fast". Measure first;ArrayListusually wins. - Using
list.containsfor frequent lookups on large data. Use aSet.
What's next#
Lists allow duplicates and are slow to search. Next, sets guarantee uniqueness and offer lightning-fast membership checks.
Check your understanding
Quick quiz
1.Which operation is O(1) on an
ArrayListbut O(n) on aLinkedList?2.What happens if you call
list.remove(x)inside a for-each loop over the sameArrayList?3.What does
List.of("a", "b").add("c")do?
Finished reading?
Mark this lesson complete to track your progress.