Chapter 6: The List ADT and Java Collections
Introduction
Learning Outcomes
Explain the basic operations of an ordered collection.
Know when to use Iterator, ListIterator, and Spliterator.
Compare ArrayList and LinkedList.
Pick the collection and method that fit the operations you need.
Collection Interfaces
Java Collections Framework: The List Side
- An interface says what can be done; a class says how: List ADT ↔ data structure.
- Code written against the interface type can switch implementations easily:
List<String> l = new ArrayList<>();
Collection Interfaces
The Iterable Interface
At the top of the hierarchy, it lets us traverse an object's elements. If an object is Iterable, we can:
Iterator that visits the elements in order.Spliterator that splits the elements into parts for parallel processing.// what we write for (var x : a) { System.out.println(x); }
// what the compiler generates (a is Iterable) Iterator<T> it = a.iterator(); while (it.hasNext()) { var x = it.next(); System.out.println(x); }
A for-each loop compiles only if a is an array or an object of a class that implements Iterable. (For arrays it becomes an indexed loop.)
Collection Interfaces · Step through the code
Code Trace: Our Own Iterable Class
for (int x : new Range(2, 5)): the constructor runs first; the range is [2, 5).
for-each quietly calls iterator(): an anonymous inner class, k = start.
hasNext(): 2 < 5 → true
next(): returns 2, then k++ → 3. The body prints x = 2.
hasNext(): 3 < 5 → true
next(): returns 3, then k++ → 4. The body prints x = 3.
hasNext(): 4 < 5 → true
next(): returns 4, then k++ → 5. The body prints x = 4.
hasNext(): 5 < 5 → false; the loop ends.
The contract: next() with no elements left → NoSuchElementException.
class Range implements Iterable<Integer> { private final int start, end; Range(int s, int e) { start = s; end = e; } public Iterator<Integer> iterator() { return new Iterator<Integer>() { int k = start; public boolean hasNext() { return k < end; } public Integer next() { if (k >= end) throw new NoSuchElementException(); return k++; } }; } }
Collection Interfaces
The Collection Interface
It standardizes what every collection (list, set, queue) can do:
| Capability | Methods | Example |
|---|---|---|
| Adding / removing elements | add(e), remove(o), clear() | c.add("Ann") → true |
| Size and emptiness | size(), isEmpty() | c.size() → 1 |
| Membership test | contains(o) | c.contains("Ann") → true |
| Stream processing | stream() | c.stream().count() |
| Copying to an array | toArray() | c.toArray(new String[0]) |
| Bulk operations | addAll, removeAll, removeIf | c.removeIf(s -> s.isEmpty()) |
A Collection has no indices: position-based operations such as get(i) come with the List interface.
Collection Interfaces
The List Interface
- Part of the Java Collections Framework, in the
java.utilpackage. - An ordered collection (a sequence): elements stay where they were inserted.
- The user decides where each element goes and reaches it by an integer index, starting at 0.
- Allows duplicates and, in most implementations,
null. - Supports searching:
indexOf,contains.
new List() won't compile; we use a class that implements it (ArrayList, LinkedList, …).The List ADT
List Terminology
isEmpty() → true.size(). Not to be confused with capacity.The List ADT
List Operations: The ADT and Java
| ADT operation | Meaning | Java List method |
|---|---|---|
| Append | adds an element at the end | add(e) |
| Insert | adds at a given position; later elements shift | add(i, e) |
| Remove | removes the element at a position, or a given element | remove(i), remove(o) |
| Indexing | reads / replaces the element at a position | get(i), set(i, e) |
| Slicing | selects a range [start, end) | subList(from, to) |
| Search | finds an element's position | indexOf(o) → −1 if absent |
| Length | returns the number of elements | size() |
subList is not a copy but a view of the original list: l.subList(1, 3).clear() removes the elements at indices 1 and 2 from the original.
The List ADT · Step through the code
Code Trace: subList Is a View
An ArrayList with 5 elements.
subList(1, 3) makes no copy: it is a view that stores only a start (offset) and a length. [1, 3) → B, C.
Printing the view reads indices 1 and 2 of the original list.
sub.set(0, …) → l.set(offset + 0, …) on the original: l[1] = X.
sub.add("Y") appends to the view, which means inserting at index 3 of l; D and E shift right and the view grows.
sub.clear() removes the view's 3 elements (indices 1–3) from the original list…
…and D, E shift left. l.subList(a, b).clear() is the short way to delete a range.
The result is [A, D, E]. Careful: if l itself is structurally modified (add/remove), the old sub becomes invalid → ConcurrentModificationException.
List<String> l = new ArrayList<>( List.of("A", "B", "C", "D", "E")); List<String> sub = l.subList(1, 3); System.out.println(sub); sub.set(0, "X"); sub.add("Y"); sub.clear(); System.out.println(l);
The List ADT
Mutable and Immutable Lists
List<String> fixed = List.of("Ann", "Dan"); fixed.add("Ben"); // UnsupportedOperationException List<String> copy = new ArrayList<>(fixed); // mutable copy copy.add("Ben"); // [Ann, Dan, Ben]; fixed is still [Ann, Dan]
- Immutability is a core idea of functional programming: immutable data is safe to share and to use in parallel.
- Persistent data structures are immutable; each "update" keeps the old version and avoids a full copy by sharing the unchanged parts.
Collections.unmodifiableList(l)is only a read-only view: if the underlyinglchanges, so does the view.
The List ADT · Step through the code
Code Trace: Copy, View, or Immutable?
List.of builds an immutable list (and rejects null).
If uncommented: structural changes are forbidden → UnsupportedOperationException (a runtime error, not a compile error).
new ArrayList<>(fixed) copies the elements into a new array; now there are two separate objects.
The copy is mutable, so Ben is added. fixed is still [Ann, Dan].
unmodifiableList copies nothing: it returns a view that wraps copy and refuses writes.
If uncommented: writing through the view is forbidden → UnsupportedOperationException.
But the underlying copy can change, and since the view looks at the same array, it sees the change.
Read-only ≠ immutable. For true immutability, use List.copyOf(copy).
List<String> fixed = List.of("Ann", "Dan"); // fixed.add("Ben"); → error List<String> copy = new ArrayList<>(fixed); copy.add("Ben"); List<String> view = Collections.unmodifiableList(copy); // view.set(0, "Eve"); → error copy.set(0, "Eve"); System.out.println(view);
List Methods
Main Methods of the List Interface
| Group | Method | Description |
|---|---|---|
| Adding | add(E e) | appends; returns true |
add(int index, E e) | inserts at the index; later elements shift one place right | |
| Removing | remove(Object o) | removes the first occurrence; true if found |
remove(int index) | removes the element at the index and returns it | |
| Access | get(int index) | returns the element at the index |
set(int index, E e) | replaces the element; returns the old one | |
| Length | size() | number of elements |
index < 0 or index ≥ size(); for add, > size()) → IndexOutOfBoundsException. Loops traverse the elements (→ Traversal).List Methods
ListDemo: Duplicates and null
public class ListDemo { // import java.util.ArrayList; import java.util.List; public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Ann"); // duplicate: allowed names.add(null); // null: allowed names.add("Ann"); System.out.println(names); // [Ann, Ann, null, Ann] System.out.println(names.size()); // 4 System.out.println(names.indexOf("Ann")); // 0 (first occurrence) System.out.println(names.lastIndexOf("Ann")); // 3 } }
Set.List.of(...) rejects null.List Methods · Step through the code
Code Trace: Duplicates, null, and Search
An empty ArrayList.
Appended at index 0.
The same value goes in again: a list (unlike a set) allows duplicates.
ArrayList stores null too.
The third "Ann" goes to index 3.
toString() prints the elements in order, in square brackets.
size(): the number of elements (not the capacity).
indexOf scans from the front and stops at the first match: "Ann".equals(array[0]) → 0.
lastIndexOf scans from the back: the first index it checks, 3, matches → 3.
indexOf(null): since the target is null, it uses == instead of equals. array[0] == null? No.
array[1] == null? No.
array[2] == null? Yes → 2. (Calling null.equals would have thrown a NullPointerException.)
List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Ann"); // duplicate: allowed names.add(null); // null: allowed names.add("Ann"); System.out.println(names); System.out.println(names.size()); System.out.println(names.indexOf("Ann")); System.out.println(names.lastIndexOf("Ann")); System.out.println(names.indexOf(null));
List Methods
A Trap: remove(int) or remove(Object)?
When a list holds Integers, the two methods are easy to mix up: an int argument is taken as an index.
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30)); nums.remove(1); // removes index 1 → [10, 30] nums.remove(Integer.valueOf(10)); // removes the value 10 → [30] nums.remove(Integer.valueOf(99)); // absent → false, no change nums.remove(5); // IndexOutOfBoundsException
List Methods · Step through the code
Code Trace: Which remove Is Called?
[10, 20, 30]. On a List<Integer>, both remove overloads apply.
The argument is an int, so the compiler picks remove(int index), which needs no boxing. Index 1 goes.
30 shifts one place left; the removed element is returned: a = 20.
An Integer argument → remove(Object o): search by value. Integer.valueOf(10).equals(10) → a match at index 0.
The first match is removed and 30 shifts; the result is a boolean: b = true.
Searching for 99: 30 ≠ 99, end of list → not found, no change, c = false.
remove(5): the index check 5 < size (1) fails → IndexOutOfBoundsException: "Index 5 out of bounds for length 1".
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30)); Integer a = nums.remove(1); boolean b = nums.remove(Integer.valueOf(10)); boolean c = nums.remove(Integer.valueOf(99)); nums.remove(5); // IndexOutOfBoundsException
List Methods
Bulk Operations with Lambdas: replaceAll and sort
List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Tom"); names.add("Bob"); names.replaceAll( name -> name.toUpperCase()); System.out.println(names); // [ANN, TOM, BOB]
Each element is replaced in place by the function's result.
List<Integer> nums = new ArrayList<>(); nums.add(5); nums.add(3); nums.add(1); nums.sort((s1, s2) -> Integer.compare(s1, s2)); System.out.println(nums); // [1, 3, 5]
Shorter: nums.sort(null) or Comparator.naturalOrder(); reverse order: Comparator.reverseOrder().
Note: under a Turkish locale, toUpperCase() turns i into İ ("Kim" → "KİM"); for a locale-independent result, use toUpperCase(Locale.ROOT).
List Methods · Step through the code
Code Trace: replaceAll and sort
An ArrayList of three names.
replaceAll calls the lambda for each index and writes the result back in place: array[0] = "ANN".
replaceAll calls the lambda for each index and writes the result back in place: array[1] = "TOM".
replaceAll calls the lambda for each index and writes the result back in place: array[2] = "BOB".
[5, 3, 1]. Java's sort uses TimSort; our lambda does the comparing.
The first call, compare(3, 5) → -1: the array opens with a descending run.
compare(1, 3) → -1: the descending run continues; its length is 3.
The whole array is one descending run, so TimSort reverses it → [1, 3, 5]. Only 2 comparisons.
With Locale.ROOT the result is the same everywhere (under a Turkish locale, an i would become İ).
List<String> names = new ArrayList<>( List.of("Ann", "Tom", "Bob")); names.replaceAll( name -> name.toUpperCase(Locale.ROOT)); List<Integer> nums = new ArrayList<>( List.of(5, 3, 1)); nums.sort((s1, s2) -> Integer.compare(s1, s2)); System.out.println(names + " " + nums);
List Methods
Indexed Access and Generics
List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Tom"); names.add("Bob"); String firstName = names.get(0); System.out.println(firstName); // Ann names.get(3); // IndexOutOfBounds
List<String> names = new ArrayList<>(); names.add("Ann"); names.add(5); // compile error List<Integer> nums = new ArrayList<>(); nums.add(5); // autoboxing int x = nums.get(0); // unboxing
- Indices start at 0. The type parameter
<String>catches a wrong type at compile time, and the result ofgetneeds no cast. - A type parameter cannot be primitive: not
List<int>butList<Integer>(autoboxing).
List Methods · Step through the code
Code Trace: get, Generics, and Boxing
Type parameter <String>: only Strings can go into this list (checked at compile time).
"Ann" goes in at index 0.
"Tom" goes in at index 1.
"Bob" goes in at index 2.
get(0): the check 0 < size (3) passes and array[0] is read directly → O(1). No cast needed.
Prints Ann.
List<int> is not allowed; we use the wrapper class Integer.
Autoboxing: the compiler inserts Integer.valueOf(5); the list holds a reference to the object.
Unboxing: get(0).intValue() → the primitive 5. (A null element would throw a NullPointerException.)
get(3): 3 < size (3) is false → IndexOutOfBoundsException. Valid indices are 0 … size − 1.
List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Tom"); names.add("Bob"); String firstName = names.get(0); System.out.println(firstName); List<Integer> nums = new ArrayList<>(); nums.add(5); // Integer.valueOf(5) int x = nums.get(0); // .intValue() names.get(3); // IndexOutOfBounds
List Methods
Spliterator: A Splittable Iterator
List<String> words = new ArrayList<>(); words.add("Java"); words.add("Python"); words.add("C++"); Spliterator<String> split = words.spliterator(); while (split.tryAdvance( System.out::println)) { // each call handles one element }
tryAdvance(action): if there is a next element, applies the action and returnstrue; otherwisefalse.trySplit(): hands part of the remaining elements to a new Spliterator, so the work can be shared among threads.- Parallel streams (
parallelStream()) use Spliterators behind the scenes.
Java Python C++
List Methods · Step through the code
Code Trace: trySplit and tryAdvance
A list of 4 words.
spliterator(): index 0, fence −1 → the bound is set from size() on first use (lazily).
trySplit(): fence = 4, mid = (0 + 4) / 2 = 2. The first half [0, 2) goes to the new b; a keeps [2, 4).
b.tryAdvance: an element is left → "Java" goes to the action (println), index moves to 1; true.
b.tryAdvance: an element is left → "Python" goes to the action (println), index moves to 2; true.
b.tryAdvance: index = fence → nothing left, false; the loop ends.
a.tryAdvance: an element is left → "C++" goes to the action (println), index moves to 3; true.
a.tryAdvance: an element is left → "Go" goes to the action (println), index moves to 4; true.
a.tryAdvance: index = fence → nothing left, false; the loop ends. The two halves could just as well run on two threads.
List<String> words = new ArrayList<>( List.of("Java", "Python", "C++", "Go")); Spliterator<String> a = words.spliterator(); Spliterator<String> b = a.trySplit(); while (b.tryAdvance(System.out::println)) { } while (a.tryAdvance(System.out::println)) { }
Traversal
Three Ways to Traverse a Collection
int n = list.size(); for (int i = 0; i < n; i++) { String s = list.get(i); ... }
Lists only; when you also need the index.
list.forEach( System.out::println); // or for-each: for (String s : list) ...
Any Iterable; the shortest form.
Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); }
When you need to remove safely while traversing.
LinkedList, get(i) is O(n), so the indexed loop takes O(n²) in total; forEach / Iterator is O(n) on both lists.Traversal · Step through the code
Code Trace: The Cost of an Indexed Loop on LinkedList
A doubly linked list with 6 nodes.
steps counts how many links the get calls walk in total.
get(0): 0 < n/2 = 3 → walks from first, 0 links. Total 0.
get(1): 1 < n/2 = 3 → walks from first, 1 link. Total 1.
get(2): 2 < n/2 = 3 → walks from first, 2 links. Total 3.
get(3): 3 ≥ n/2 = 3 → walks from last, 2 links. Total 5.
get(4): 4 ≥ n/2 = 3 → walks from last, 1 link. Total 6.
get(5): 5 ≥ n/2 = 3 → walks from last, 0 links. Total 6.
Total 6 = n²/4 − n/2 ≈ n²/4 → O(n²). An Iterator walks 1 link per next(): n − 1 = 5 in total → O(n).
List<String> list = new LinkedList<>( List.of("A", "B", "C", "D", "E", "F")); int n = list.size(), steps = 0; for (int i = 0; i < n; i++) { String s = list.get(i); // node(i) walks steps += Math.min(i, n - 1 - i); } System.out.println(steps);
Traversal
The Iterator Interface
false at the end.NoSuchElementException.next() (an optional operation).iterator(): the cursor sits before the first element. hasNext() → true
next() → "Ann" (the cursor jumps over the element)
next() → "Tom"
next() → "Bob"; now hasNext() → false and the loop ends
One more next() → NoSuchElementException
while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); }
Traversal · Step through the code
Code Trace: Traversing with an Iterator
iterator(): the cursor sits before the first element (cursor = 0). The iterator is a separate object that walks the list.
hasNext(): cursor 0 ≠ size 3 → true.
next() → "Ann"; the cursor jumps over the element (cursor = 1).
Prints Ann.
hasNext(): cursor 1 ≠ size 3 → true.
next() → "Tom"; the cursor jumps over the element (cursor = 2).
Prints Tom.
hasNext(): cursor 2 ≠ size 3 → true.
next() → "Bob"; the cursor jumps over the element (cursor = 3).
Prints Bob.
cursor 3 = size 3 → hasNext() is false and the loop ends. One more next() would throw NoSuchElementException.
Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); }
Traversal
Removing While Traversing: ConcurrentModificationException
for (String s : names) if (s.startsWith("A")) names.remove(s); // ConcurrentModification- // Exception (fail-fast)
Iterator<String> it = names.iterator(); while (it.hasNext()) if (it.next().startsWith("A")) it.remove(); // or, shorter: names.removeIf(s -> s.startsWith("A"));
- for-each quietly uses an Iterator; if the list is modified behind the iterator's back, the next
next()notices and stops (fail-fast). it.remove()may be called only once pernext(); otherwiseIllegalStateException.
Traversal · Step through the code
Code Trace: ConcurrentModificationException
An empty ArrayList. Every structural change (add/remove) increments the list's modCount.
Two add calls → modCount = 2.
modCount = 3. Now we trace the for-each loop as the compiler expands it.
iterator(): cursor 0; the iterator records the current count as expectedModCount = 3.
hasNext(): cursor 0 ≠ size 3 → true.
next() first checks modCount == expectedModCount: 3 == 3 ✓ → "Ann", cursor = 1.
"Ann" starts with A → true.
names.remove(s) removes directly from the list → elements shift left, modCount = 4. The iterator doesn't know (expected is still 3).
hasNext(): cursor 1 ≠ size 2 → true. ("Ben" is now behind the cursor and would never be visited!)
next(): modCount 4 ≠ expectedModCount 3 → ConcurrentModificationException. The iterator notices the change at once and stops (fail-fast).
List<String> names = new ArrayList<>(); names.add("Ann"); names.add("Ben"); names.add("Alice"); // modCount = 3 // for (String s : names) ... compiled: Iterator<String> it = names.iterator(); while (it.hasNext()) { String s = it.next(); if (s.startsWith("A")) names.remove(s); // not through it! }
Traversal · Step through the code
Code Trace: Safe Removal with it.remove()
The same list [Ann, Ben, Alice], modCount = 3. Iterator: cursor = 0, lastRet = −1 (nothing returned yet).
hasNext(): cursor 0 ≠ size 3 → true.
next(): 3 == 3 ✓ → "Ann"; cursor = 1, lastRet = 0.
Does "Ann" start with A? Yes.
it.remove() removes the element at lastRet; cursor = 0 (the shifted element is not skipped), lastRet = −1, expectedModCount = modCount = 4.
hasNext(): cursor 0 ≠ size 2 → true.
next(): 4 == 4 ✓ → "Ben"; cursor = 1, lastRet = 0.
Does "Ben" start with A? No.
hasNext(): cursor 1 ≠ size 2 → true.
next(): 4 == 4 ✓ → "Alice"; cursor = 2, lastRet = 1.
Does "Alice" start with A? Yes.
it.remove() removes the element at lastRet; cursor = 1 (the shifted element is not skipped), lastRet = −1, expectedModCount = modCount = 5.
hasNext(): cursor 1 = size 1 → false. The loop ends with no error.
The result is [Ben]: the names starting with A were removed safely. A second it.remove() with no next() in between → IllegalStateException.
Iterator<String> it = names.iterator(); while (it.hasNext()) { String s = it.next(); if (s.startsWith("A")) it.remove(); // keeps the counts in sync } System.out.println(names);
Traversal
The ListIterator Interface
Available only on Lists (list.listIterator()). Beyond what an Iterator does, it moves in both directions and can add, remove, and replace elements on the way. The cursor sits between elements.
| Method | What it does |
|---|---|
hasNext() / next() | is there an element ahead? / return the next element and move the cursor forward |
hasPrevious() / previous() | is there an element behind? / return the previous element and move the cursor back |
nextIndex() / previousIndex() | the index of the element next() / previous() would return (0 / −1 at the start) |
add(e) | inserts the element before the cursor (the next next() is unaffected) |
remove() | removes the element returned by the last next()/previous() |
set(e) | replaces the element returned by the last next()/previous() |
Calling remove/set right after add or remove, with no next/previous in between → IllegalStateException.
Traversal · Step through the code
Code Trace: ListIterator, Step by Step
listIterator(): the cursor is at the start; nextIndex = 0, previousIndex = −1. Orange: the last returned element (lastRet).
next() → "Ann"; the cursor moves forward, lastRet = 0.
next() → "Tom"; lastRet = 1.
set("TOM") replaces the element at lastRet ("Tom"); the cursor stays put.
add("Alice") inserts before the cursor, and the cursor moves past the new element (the next next still returns "Bob"); lastRet = −1.
previous() → "Alice", moving backward; the cursor steps back, lastRet = 2.
remove() deletes "Alice" at lastRet; lastRet = −1 (an immediate second remove/set → IllegalStateException).
ListIterator<String> it = names.listIterator(); it.next(); // "Ann" it.next(); // "Tom" it.set("TOM"); // [Ann, TOM, Bob] it.add("Alice"); // [Ann, TOM, Alice, Bob] it.previous(); // "Alice" it.remove(); // [Ann, TOM, Bob]
Traversal
ListIterator Demo: Forward and Backward
ListIterator<String> iterator = names.listIterator(); // traverse the list forward while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); } // cursor is now at the end: go backward while (iterator.hasPrevious()) { String name = iterator.previous(); System.out.println(name); }
Ann Tom Bob Bob Tom Ann
The second loop reuses the same iterator: when the first loop ends, the cursor is at the end of the list.
To start at the end directly: names.listIterator(names.size()).
Traversal · Step through the code
Code Trace: Forward and Backward
listIterator(): the cursor is at the start.
hasNext() → true (cursor 0 < 3).
next() → "Ann", printed; the cursor moves forward.
hasNext() → true (cursor 1 < 3).
next() → "Tom", printed; the cursor moves forward.
hasNext() → true (cursor 2 < 3).
next() → "Bob", printed; the cursor moves forward.
hasNext() → false: the cursor is at the end. The first loop ends; we continue with the same iterator.
hasPrevious() → true (cursor 3 > 0).
previous() → "Bob", printed; the cursor moves back.
hasPrevious() → true (cursor 2 > 0).
previous() → "Tom", printed; the cursor moves back.
hasPrevious() → true (cursor 1 > 0).
previous() → "Ann", printed; the cursor moves back.
hasPrevious() → false: the cursor is back at the start. Output: 3 lines forward + 3 backward.
ListIterator<String> iterator = names.listIterator(); // traverse the list forward while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); } // cursor is now at the end: go backward while (iterator.hasPrevious()) { String name = iterator.previous(); System.out.println(name); }
List Implementations
Classes That Implement List
List Implementations
ArrayList: A Growable Array
- Keeps its elements in an internal array. Capacity (array length) ≥ size (number of elements).
- When the array fills up, a new one about 1.5 times larger is created and the elements are copied (O(n)). Since this is rare, appending is amortized O(1).
- It does not shrink on removal;
trimToSize()cuts the capacity down to the size.
Real Java: an empty new ArrayList<>() gets capacity 10 on the first add; new capacity = old + old/2. The demo starts at 4.
List Implementations · Step through the code
Code Trace: ArrayList add(e) and Growth
Capacity 4, size 3 (a demo; real Java starts an empty list at 10 on the first add). We add D, E, F, G in turn.
add(D): size 3 == capacity 4? No.
data[3] = D, size = 4; returns true.
add(E): size 4 == capacity 4? Yes → the array is full.
newCap = 4 + 4 / 2 = 6: about 1.5 times (Java: old + old >> 1).
Arrays.copyOf: a new array with 6 slots; the 4 elements are copied one by one → this add is O(n). The old array becomes garbage.
data[4] = E, size = 5; returns true.
add(F): size 5 == capacity 6? No.
data[5] = F, size = 6; returns true.
add(G): size 6 == capacity 6? Yes → the array is full.
newCap = 6 + 6 / 2 = 9: about 1.5 times (Java: old + old >> 1).
Arrays.copyOf: a new array with 9 slots; the 6 elements are copied one by one → this add is O(n). The old array becomes garbage.
data[6] = G, size = 7; returns true. Because the capacity grows by 1.5 times each time, resizes get rarer and rarer: n adds copy O(n) elements in total → an add is amortized O(1).
public boolean add(E e) { if (size == data.length) { int newCap = Math.max(data.length + 1, data.length + data.length / 2); data = Arrays.copyOf(data, newCap); } data[size++] = e; return true; }
List Implementations
Amortized Analysis: Why Grow Geometrically?
- Doubling (×2): n adds copy 4 + 8 + 16 + … < 2n elements → amortized O(1) per operation.
- Java's ×1.5 is geometric growth too: about 3n in total (integer division can shift this slightly), still amortized O(1).
- Fixed increments (+c): c + 2c + 3c + … ≈ n²/(2c) copies → O(n) per operation.
- Goodrich–Tamassia's "banker's" method: each cheap add deposits a few "tokens," and those tokens pay for the expensive resize.
The chart shows copies actually counted over 40 adds to a dynamic array that starts at capacity 4.
List Implementations
Using ArrayList: Operations and Costs
ArrayList<String> list = new ArrayList<>(); list.add("Ann"); // [Ann] list.add("Dan"); // [Ann, Dan] list.add(0, "Ben"); // [Ben, Ann, Dan] list.get(1); // "Ann" list.remove(0); // [Ann, Dan] list.size(); // 2
| Operation | Cost |
|---|---|
get(i), set(i, e) | O(1) |
add(e) (at the end) | amortized O(1) |
add(i, e), remove(i) | O(n) |
contains, indexOf | O(n) |
size() | O(1) |
List Implementations · Step through the code
Code Trace: What ArrayList Operations Cost
An empty new ArrayList<>(): the internal array starts empty; the first add allocates one of capacity 10.
The first add creates an array of 10 and puts Ann at index 0. Appending needs no shifting.
Dan goes to index 1 (amortized O(1)).
add(0, …): first the 2 elements from index 0 on shift one place right (starting from the right).
Ben goes into the freed index 0. Inserting at the front costs n shifts → O(n).
get(1): direct access by address arithmetic → O(1), no shifting.
remove(0): Ben is about to go…
…the next 2 elements shift left and the last cell is set to null. The capacity does not shrink.
size() = 2: it reads a counter field, O(1). All 4 shifts came from operations at the front.
ArrayList<String> list = new ArrayList<>(); list.add("Ann"); list.add("Dan"); list.add(0, "Ben"); String s = list.get(1); list.remove(0); int n = list.size();
List Implementations · Step through the code
Code Trace: ArrayList add(i, e)
[A, B, C, D], capacity 6. add(1, "X"): X goes to index 1, so B, C, D must shift one place right.
0 ≤ 1 ≤ size (4) → a valid index (otherwise IndexOutOfBoundsException).
size 4 < capacity 6 → no need to grow.
k = 4 > 1: data[4] = data[3] → D is copied right. We start from the right so nothing is overwritten.
k = 3 > 1: data[3] = data[2] → C is copied right. We start from the right so nothing is overwritten.
k = 2 > 1: data[2] = data[1] → B is copied right. We start from the right so nothing is overwritten.
k = 1 > 1 is false → the loop ends. data[1] still holds the old copy of B.
data[1] = X fills the gap.
size = 5. n − i = 3 shifts → O(n); inserting at the front shifts the whole list.
public void add(int i, E e) { Objects.checkIndex(i, size + 1); if (size == data.length) resize(); for (int k = size; k > i; k--) data[k] = data[k - 1]; data[i] = e; size++; }
List Implementations · Step through the code
Code Trace: ArrayList remove(i)
The list is [A, X, B, C, D]. remove(1): X goes, so B, C, D must shift left.
0 ≤ 1 < size (5) → a valid index.
old = data[1] = X (to be returned).
k = 1 < 4: data[1] = data[2] → B shifts left. This time we start from the left.
k = 2 < 4: data[2] = data[3] → C shifts left. This time we start from the left.
k = 3 < 4: data[3] = data[4] → D shifts left. This time we start from the left.
k = 4 < 4 is false → the loop ends. D now appears twice at the end.
data[--size] = null: size 4; the extra reference is cleared (preventing a memory leak). The capacity does not shrink.
return X. n − i − 1 = 3 shifts → O(n). Removing the last element (i = size − 1) is O(1).
public E remove(int i) { Objects.checkIndex(i, size); E old = data[i]; for (int k = i; k < size - 1; k++) data[k] = data[k + 1]; data[--size] = null; return old; }
List Implementations
LinkedList: A Doubly Linked List
- Elements are not contiguous in memory: each one lives in its own node object.
- Each node holds its data and references to the previous / next nodes; the list knows
firstandlast. - Besides
List, it implementsDeque, so it can serve as a stack or a queue. - Random access is slow:
get(i)walks node by node (from the nearer end) → O(n).
List Implementations
Using LinkedList: Operations and Costs
LinkedList<String> list = new LinkedList<>(); list.add("B"); // [B] list.addFirst("A"); // [A, B] list.addLast("C"); // [A, B, C] list.get(1); // "B" (by walking) list.removeFirst(); // [B, C] list.size(); // 2
| Operation | Cost |
|---|---|
| add / remove at either end | O(1) |
get(i), set(i, e) | O(n) |
add(i, e), remove(i) | O(n)* |
| add / remove through an iterator | O(1) |
List Implementations · Step through the code
Code Trace: What LinkedList Operations Cost
An empty LinkedList: no nodes; first and last are null.
add = addLast: a single node, and both first and last point to it.
addFirst: a new node; A.next = B, B.prev = A, first = A → O(1), no shifting.
addLast: thanks to last, no walk to the end is needed → O(1).
get(1) → node(1): 1 < size/2 = 1 is false → start from the end: x = last (C).
x = x.prev → B, the node we want, after walking 1 link. O(n) in general.
removeFirst: A is about to be unlinked.
first = B, B.prev = null; nothing refers to A any more, so the garbage collector reclaims it → O(1).
size() reads a counter field: O(1).
LinkedList<String> list = new LinkedList<>(); list.add("B"); list.addFirst("A"); list.addLast("C"); String s = list.get(1); list.removeFirst(); int n = list.size();
List Implementations · Step through the code
Code Trace: LinkedList addLast(e)
An empty LinkedList. addLast("A"), then addLast("B") (the same logic as Java's linkLast).
l = last = null: remember the old last node.
A new node: prev = l (null), next = null.
last = n.
l == null (the list was empty) → first = n: the only node is both first and last.
size = 1.
l = last = node(A): remember the old last node.
A new node: prev = l (node(A)), next = null. The back link is set at construction.
last = n.
l is not null → else.
l.next = n: the forward link A → B.
size = 2. No traversal: appending is O(1).
void addLast(E e) { Node<E> l = last; Node<E> n = new Node<>(l, e, null); last = n; if (l == null) first = n; else l.next = n; size++; }
List Implementations · Step through the code
Code Trace: LinkedList remove(i)
[A, B, C]. remove(1): to find B, we first have to walk.
0 ≤ 1 < 3 → a valid index.
x = first (A). There is no direct indexed access as in an array.
k = 0 < 1: x = x.next → B.
k = 1 < 1 is false → the walk ends after i steps: O(i). (If i ≥ size/2, Java walks backward from last.)
p = x.prev = A, s = x.next = C: the two neighbors of the node to remove.
p is not null → p.next = s: A now points straight to C (B is bypassed).
s is not null → s.prev = p: C points back to A. B is cut off in both directions.
size = 2.
return "B". Relinking is O(1), but walking is O(n) → remove(i) is O(n) overall.
E remove(int i) { Objects.checkIndex(i, size); Node<E> x = first; for (int k = 0; k < i; k++) x = x.next; Node<E> p = x.prev, s = x.next; if (p == null) first = s; else p.next = s; if (s == null) last = p; else s.prev = p; size--; return x.data; }
List Implementations
The Positional List ADT
- Indices shift on insertion and removal; a position stays with its element, like the cursor in a text editor.
- Goodrich–Tamassia:
Position<E>offers onlygetElement(); in a linked implementation, a position is a node. - Thanks to the sentinel nodes header and trailer, every insertion happens between two real nodes: no null checks.
| Method | Cost |
|---|---|
first(), last(), before(p), after(p) | O(1) |
addFirst(e), addLast(e) | O(1) |
addBefore(p, e), addAfter(p, e) | O(1) |
set(p, e), remove(p) | O(1) |
Java has no direct equivalent; the closest is ListIterator (O(1) insertion/removal next to the cursor).
List Implementations · Step through the code
Code Trace: Positional List addAfter(p, e)
header ⇄ A ⇄ C ⇄ trailer; p is the position of A. We call addAfter(p, "B").
validate(p): is p a valid node of this list? Yes → it is cast to a Node.
The neighbors are known: pred = A, succ = A.next = C. The work is handed to addBetween.
The new node points to both neighbors, but nothing points to it yet.
pred.next = newest: forward, A → B → C.
succ.prev = newest: backward, C → B → A. The old A ⇄ C links are gone.
size++. No walking, no shifting: 4 assignments → O(1).
It returns the new element's position, ready for later calls such as addBefore or remove.
Position<E> addAfter(Position<E> p, E e) {
Node<E> n = validate(p);
return addBetween(e, n, n.next);
}
Position<E> addBetween(E e, Node<E> pred, Node<E> succ) {
Node<E> newest = new Node<>(pred, e, succ);
pred.next = newest;
succ.prev = newest;
size++;
return newest;
}
List Implementations
ArrayList or LinkedList?
| ArrayList | LinkedList | |
|---|---|---|
| Internals | growable array | doubly linked nodes |
| get(i) | O(1) | O(n) |
| Append | amortized O(1) | O(1) |
| Add / remove at the front | O(n) | O(1) |
| Memory per element | 1 reference (+ spare capacity) | a node object (3 references) |
| Cache behavior | contiguous, fast | scattered, slow |
List Implementations
ArrayList and LinkedList in Memory
About 1 reference per element (4–8 bytes) + spare capacity. The array is contiguous, so the CPU cache prefetches the next elements.
One node object per element: an object header + 3 references (~24–40 bytes). Following each next may cause a cache miss.
List Implementations
Vector
- A growable array like ArrayList: indexed access, grows as needed (by default the capacity doubles).
- Its methods are
synchronized, so individual operations are thread-safe. - The price: every call pays for a lock, even with a single thread.
- Compound operations such as "check, then act" are still not atomic.
Vector<Integer> v = new Vector<>(); v.add(10); // [10] v.add(20); // [10, 20] v.get(0); // 10 v.remove(0); // [20] v.size(); // 1 v.capacity(); // 10 // compound action: needs an external lock synchronized (v) { if (!v.isEmpty()) v.remove(0); }
ArrayList for a single thread, and Collections.synchronizedList or CopyOnWriteArrayList for many.List Implementations
Vector: The "Check, Then Act" Race
Every Vector method is synchronized, but the gap between two calls is unprotected. One possible interleaving of two threads:
Start: v = [20]. Both threads will run if (!v.isEmpty()) v.remove(0);.
T1: isEmpty() takes the lock, returns false, and releases the lock.
T2 slips in: v still has 1 element, so it sees false too. Both think they can remove.
T1: remove(0) → 20. v is now empty.
T2: remove(0) on an empty vector → ArrayIndexOutOfBoundsException. Each method is synchronized on its own, but the pair is not atomic.
The fix: put the compound action under one lock with synchronized (v) { … }. T2 waits until T1 leaves the block.
When T2 gets the lock, it sees v is empty and does not remove: "check, then act" is now safe.
List Implementations
The Stack Class
- Extends Vector and implements a last-in, first-out (LIFO) stack.
- Operations act on the top element; handy for undo/redo.
push(e) | adds on top |
pop() | removes and returns the top |
peek() | returns the top without removing it |
empty() | is the stack empty? |
search(o) | distance from the top, starting at 1; −1 if absent |
pop/peek on an empty stack → EmptyStackException.
get(i) and add(i, e), and it pays for synchronization. The Java documentation recommends Deque<E> s = new ArrayDeque<>(); for a stack.List Implementations
CopyOnWriteArrayList: Copy on Write
- On every change (add, set, remove), the internal array is copied, the change is made on the copy, and the list then switches to the new array.
- Reads take no lock and are very fast; writes queue up behind a short lock and pay an O(n) copy.
Readers read the internal array without locking; each iterator walks the array as it was when the iterator was created (a snapshot).
add("d"): the writer takes the lock, copies the array, and appends the new element to the copy → O(n)
The list reference switches to the new array. The old iterator keeps walking A: no ConcurrentModificationException.
it.remove() is not supported.List Implementations · Step through the code
Code Trace: CopyOnWriteArrayList add(e)
The list points to A = [a, b, c]. An iterator has walked over A and read "a" (cursor 1). Now add("d").
Writers take the lock, so two writers cannot overwrite each other's copies. Readers never wait for the lock.
old = array: the current array, A.
n = 3.
Arrays.copyOf(old, 4): every element is copied into the copy array → O(n). A is left untouched.
copy[3] = "d": the change happens only in the copy.
array = copy: a single reference assignment; the list now points to B. The iterator is still on A.
Returns true and releases the lock.
The iterator's it.next() → "b", then "c": it walks its snapshot (A), never sees "d", and throws no ConcurrentModificationException.
A new iterator() sees B: [a, b, c, d]. Once the old iterator is done, nothing refers to A, and the garbage collector reclaims it.
public boolean add(E e) { synchronized (lock) { Object[] old = array; int n = old.length; Object[] copy = Arrays.copyOf(old, n + 1); copy[n] = e; array = copy; // one reference assignment return true; } }
List Implementations
Arrays.asList(): A List View of an Array
- Lets us use an array through the
Listinterface; nothing is copied, and the array and the list share the same memory. - The list is fixed-size but not immutable:
setworks (and shows up in the array);add/removedo not.
String[] array = {"a", "b", "c"}; List<String> list = Arrays.asList(array); list.set(0, "x"); // works: array[0] is now "x" too array[2] = "z"; // the list changes too → [x, b, z] list.add("d"); // UnsupportedOperationException (fixed size) List<String> copy = new ArrayList<>(Arrays.asList(array)); // independent copy
| set | add / remove | Link to the array | |
|---|---|---|---|
Arrays.asList(array) | ✓ | ✗ | shared |
List.of(...) | ✗ | ✗ | none (immutable) |
new ArrayList<>(...) | ✓ | ✓ | none (copy) |
List Implementations · Step through the code
Code Trace: The Arrays.asList View
An array of 3 elements.
Arrays.asList copies nothing: the returned list is a view wrapping the same array → O(1).
list.set(0, "x") writes into the array: array[0] is x too.
It works the other way too: writing to the array changes the list.
If uncommented: the array's length cannot change, so add/remove → UnsupportedOperationException.
For an independent, growable list, copy it: new ArrayList<>(list) allocates a new array.
Adding to the copy is fine; array and list are unaffected.
The result: two separate lists.
String[] array = {"a", "b", "c"}; List<String> list = Arrays.asList(array); list.set(0, "x"); array[2] = "z"; // list.add("d"); → error (fixed size) List<String> copy = new ArrayList<>(list); copy.add("d"); System.out.println(list + " " + copy);
Summary
Summary: List Implementations
| Class | get(i) | append | front / middle | Threads |
|---|---|---|---|---|
| ArrayList | O(1) | amortized O(1) | O(n) | not safe |
| LinkedList | O(n) | O(1) | O(1) / O(n) | not safe |
| Vector | O(1) | amortized O(1) | O(n) | synchronized |
| Stack | O(1) | push O(1) | — | synchronized |
| CopyOnWriteArrayList | O(1) | O(n) | O(n) | safe (by copying) |
| Arrays.asList | O(1) | ✗ | ✗ | not safe |
it.remove() or removeIf.Summary
Sample Problems
- What is the list after
List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); l.remove(1);? - What does it cost to traverse a
LinkedListwithfor (int i…) get(i)? What is better? - What happens when we add an element to an ArrayList with capacity 10 that holds 10 elements?
- Why does
Arrays.asList(array).add(x)fail? Why doesn'tset? - Which class suits a listener list that is read often, rarely changes, and is shared by many threads?
- On [A, B, C], after
it = listIterator(); it.next(); it.add("X");, what are the list andit.next()?
Show answers
- [5, 7]: an
intargument counts as an index (remove(int)). - O(n²); with for-each or an Iterator, O(n).
- A new array about 1.5 times larger (capacity 15) is created, the 10 elements are copied, and then the new one is added (this step is O(n); amortized, O(1)).
- The list is backed by the array and has a fixed size;
setdoesn't change the size, it just writes into the array. CopyOnWriteArrayList.- [A, X, B, C];
it.next()→ "B" (addinserts before the cursor).
Summary
Exercises
l = [A, B, C, D]; what islafterl.subList(1, 3).clear();? And what if we then calll.add("E")and read the old view?- A dynamic array grows by 2 every time it fills up. How many copies do n adds make in total?
- Which contract would break if
Range.next()skipped thek >= endcheck? - Why is
remove(p)O(1) in a positional list butLinkedList.remove(int)O(n)? l = new ArrayList<>(List.of(3, 1, 2)); l.remove(Integer.valueOf(1)); l.remove(1);→l?
Answers / hints
- [A, D]. Once
litself changes, the old view becomes invalid →ConcurrentModificationException. - 2 + 4 + 6 + … ≈ n²/4 → O(n²) in total, O(n) per operation: fixed increments don't give amortized O(1).
- The contract to throw
NoSuchElementExceptionwhen no elements are left; it would return values outside the range. - The position is the node itself (4 link assignments); removing by index first walks to node i.
- [3, 2]; then
remove(1)removes by index → [3].
Summary
Further Reading
- Oracle, Java SE 17 API documentation for
Collection,List,Iterator,ListIterator, andSpliterator. - Bloch, Effective Java, 3rd ed., 2018.
- Goodrich, Tamassia, and Goldwasser, Data Structures and Algorithms in Java, 6th ed., 2014.