Chapter 6: The List ADT and Java Collections

Data Structures
The List ADTIterable and CollectionThe List interface Iterator and ListIteratorArrayListLinkedList Positional listsVector and StackCopyOnWriteArrayListArrays.asList
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

The List ADT

Explain the basic operations of an ordered collection.

Traversal

Know when to use Iterator, ListIterator, and Spliterator.

Implementations

Compare ArrayList and LinkedList.

Choosing an API

Pick the collection and method that fit the operations you need.

Collection Interfaces

Java Collections Framework: The List Side

Iterable Collection Set List Queue ArrayList LinkedList Vector CopyOnWriteArrayList Stack rounded: interface · square: class dashed arrow: LinkedList is also a Deque
  • 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()get an Iterator that visits the elements in order.
spliterator()get a Spliterator that splits the elements into parts for parallel processing.
forEach(...)run an action (a lambda) on every element.
// 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

new Range(2, 5) · orange: last returned234end=5

for (int x : new Range(2, 5)): the constructor runs first; the range is [2, 5).

new Range(2, 5) · orange: last returned234end=5k=2

for-each quietly calls iterator(): an anonymous inner class, k = start.

new Range(2, 5) · orange: last returned234end=5k=2

hasNext(): 2 < 5 → true

new Range(2, 5) · orange: last returned234end=5k=3

next(): returns 2, then k++ → 3. The body prints x = 2.

new Range(2, 5) · orange: last returned234end=5k=3

hasNext(): 3 < 5 → true

new Range(2, 5) · orange: last returned234end=5k=4

next(): returns 3, then k++ → 4. The body prints x = 3.

new Range(2, 5) · orange: last returned234end=5k=4

hasNext(): 4 < 5 → true

new Range(2, 5) · orange: last returned234end=5k=5

next(): returns 4, then k++ → 5. The body prints x = 4.

new Range(2, 5) · orange: last returned234end=5k=5

hasNext(): 5 < 5 → false; the loop ends.

new Range(2, 5) · orange: last returned234end=5k=5

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:

CapabilityMethodsExample
Adding / removing elementsadd(e), remove(o), clear()c.add("Ann") → true
Size and emptinesssize(), isEmpty()c.size() → 1
Membership testcontains(o)c.contains("Ann") → true
Stream processingstream()c.stream().count()
Copying to an arraytoArray()c.toArray(new String[0])
Bulk operationsaddAll, removeAll, removeIfc.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.util package.
  • 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.
List is an interface, so new List() won't compile; we use a class that implements it (ArrayList, LinkedList, …).

The List ADT

List Terminology

"Ann" 0 "Dan" 1 "Alice" 2 "Ben" 3 index element length: size() = 4 [ ] empty list: size() = 0
ElementA piece of data stored in the list.
IndexThe number giving an element's position: 0 … length − 1.
Empty listA list with no elements: isEmpty() → true.
LengthThe number of elements: size(). Not to be confused with capacity.

The List ADT

List Operations: The ADT and Java

ADT operationMeaningJava List method
Appendadds an element at the endadd(e)
Insertadds at a given position; later elements shiftadd(i, e)
Removeremoves the element at a position, or a given elementremove(i), remove(o)
Indexingreads / replaces the element at a positionget(i), set(i, e)
Slicingselects a range [start, end)subList(from, to)
Searchfinds an element's positionindexOf(o) → −1 if absent
Lengthreturns the number of elementssize()

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

l0A1B2C3D4E5

An ArrayList with 5 elements.

l0A1B2C3D4E5sub: offset=1, size=2

subList(1, 3) makes no copy: it is a view that stores only a start (offset) and a length. [1, 3) → B, C.

l0A1B2C3D4E5sub: offset=1, size=2

Printing the view reads indices 1 and 2 of the original list.

l0A1X2C3D4E5sub: offset=1, size=2

sub.set(0, …) → l.set(offset + 0, …) on the original: l[1] = X.

l0A1X2C3Y4D5Esub: offset=1, size=3

sub.add("Y") appends to the view, which means inserting at index 3 of l; D and E shift right and the view grows.

l0A1X2C3Y4D5Esub: offset=1, size=3

sub.clear() removes the view's 3 elements (indices 1–3) from the original list…

l0A1D2E345sub: offset=1, size=0

…and D, E shift left. l.subList(a, b).clear() is the short way to delete a range.

l0A1D2E345sub: offset=1, size=0

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

MutableElements can be added, removed, and replaced after creation.new ArrayList<>(), new LinkedList<>()
ImmutableThe contents never change after creation; to "change" it, we build a new list.List.of(...), List.copyOf(...)
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 underlying l changes, so does the view.

The List ADT · Step through the code

Code Trace: Copy, View, or Immutable?

fixedcopyviewAnnDanList.of: immutable

List.of builds an immutable list (and rejects null).

fixedcopyviewAnnDanList.of: immutable

If uncommented: structural changes are forbidden → UnsupportedOperationException (a runtime error, not a compile error).

fixedcopyviewAnnDanList.of: immutableAnnDanArrayList (new array)

new ArrayList<>(fixed) copies the elements into a new array; now there are two separate objects.

fixedcopyviewAnnDanList.of: immutableAnnDanBenArrayList: independent copy

The copy is mutable, so Ben is added. fixed is still [Ann, Dan].

fixedcopyviewAnnDanList.of: immutableAnnDanBenArrayList: independent copyread-only wrapper

unmodifiableList copies nothing: it returns a view that wraps copy and refuses writes.

fixedcopyviewAnnDanList.of: immutableAnnDanBenArrayList: independent copyread-only wrapper

If uncommented: writing through the view is forbidden → UnsupportedOperationException.

fixedcopyviewAnnDanList.of: immutableEveDanBenArrayList: independent copyread-only wrapper

But the underlying copy can change, and since the view looks at the same array, it sees the change.

fixedcopyviewAnnDanList.of: immutableEveDanBenArrayList: independent copyread-only wrapper

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

GroupMethodDescription
Addingadd(E e)appends; returns true
add(int index, E e)inserts at the index; later elements shift one place right
Removingremove(Object o)removes the first occurrence; true if found
remove(int index)removes the element at the index and returns it
Accessget(int index)returns the element at the index
set(int index, E e)replaces the element; returns the old one
Lengthsize()number of elements
An invalid index (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
    }
}
List ≠ SetA list allows duplicates; for unique elements, use a Set.
CarefulA list built with List.of(...) rejects null.

List Methods · Step through the code

Code Trace: Duplicates, null, and Search

array012345size = 0

An empty ArrayList.

array0"Ann"12345size = 1

Appended at index 0.

array0"Ann"1"Ann"2345size = 2

The same value goes in again: a list (unlike a set) allows duplicates.

array0"Ann"1"Ann"2null345size = 3

ArrayList stores null too.

array0"Ann"1"Ann"2null3"Ann"45size = 4

The third "Ann" goes to index 3.

array0"Ann"1"Ann"2null3"Ann"45size = 4

toString() prints the elements in order, in square brackets.

array0"Ann"1"Ann"2null3"Ann"45size = 4

size(): the number of elements (not the capacity).

array0"Ann"1"Ann"2null3"Ann"45isize = 4

indexOf scans from the front and stops at the first match: "Ann".equals(array[0]) → 0.

array0"Ann"1"Ann"2null3"Ann"45isize = 4

lastIndexOf scans from the back: the first index it checks, 3, matches → 3.

array0"Ann"1"Ann"2null3"Ann"45isize = 4

indexOf(null): since the target is null, it uses == instead of equals. array[0] == null? No.

array0"Ann"1"Ann"2null3"Ann"45isize = 4

array[1] == null? No.

array0"Ann"1"Ann"2null3"Ann"45isize = 4

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
remove(int index)Returns the removed element.E remove(int)
remove(Object o)Returns whether anything was removed.boolean remove(Object)
CostIn an array-based list, both shift the later elements.O(n)

List Methods · Step through the code

Code Trace: Which remove Is Called?

nums0101202303size = 3

[10, 20, 30]. On a List<Integer>, both remove overloads apply.

nums0101202303size = 3

The argument is an int, so the compiler picks remove(int index), which needs no boxing. Index 1 goes.

nums01013023size = 2

30 shifts one place left; the removed element is returned: a = 20.

nums01013023size = 2i

An Integer argument → remove(Object o): search by value. Integer.valueOf(10).equals(10) → a match at index 0.

nums030123size = 1

The first match is removed and 30 shifts; the result is a boolean: b = true.

nums030123size = 1i

Searching for 99: 30 ≠ 99, end of list → not found, no change, c = false.

nums030123size = 1

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

replaceAll
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.

sort
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

names0Ann1Tom2Bob

An ArrayList of three names.

names0ANN1Tom2Bob

replaceAll calls the lambda for each index and writes the result back in place: array[0] = "ANN".

names0ANN1TOM2Bob

replaceAll calls the lambda for each index and writes the result back in place: array[1] = "TOM".

names0ANN1TOM2BOB

replaceAll calls the lambda for each index and writes the result back in place: array[2] = "BOB".

names0ANN1TOM2BOBnums531

[5, 3, 1]. Java's sort uses TimSort; our lambda does the comparing.

names0ANN1TOM2BOBnums531

The first call, compare(3, 5) → -1: the array opens with a descending run.

names0ANN1TOM2BOBnums531

compare(1, 3) → -1: the descending run continues; its length is 3.

names0ANN1TOM2BOBnums135

The whole array is one descending run, so TimSort reverses it → [1, 3, 5]. Only 2 comparisons.

names0ANN1TOM2BOBnums135

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 of get needs no cast.
  • A type parameter cannot be primitive: not List<int> but List<Integer> (autoboxing).

List Methods · Step through the code

Code Trace: get, Generics, and Boxing

names0123

Type parameter <String>: only Strings can go into this list (checked at compile time).

names0"Ann"123

"Ann" goes in at index 0.

names0"Ann"1"Tom"23

"Tom" goes in at index 1.

names0"Ann"1"Tom"2"Bob"3

"Bob" goes in at index 2.

names0"Ann"1"Tom"2"Bob"3get(0)

get(0): the check 0 < size (3) passes and array[0] is read directly → O(1). No cast needed.

names0"Ann"1"Tom"2"Bob"3

Prints Ann.

names0"Ann"1"Tom"2"Bob"3nums

List<int> is not allowed; we use the wrapper class Integer.

names0"Ann"1"Tom"2"Bob"3nums•Integer: 5object on the heap

Autoboxing: the compiler inserts Integer.valueOf(5); the list holds a reference to the object.

names0"Ann"1"Tom"2"Bob"3nums•Integer: 5object on the heap5int x (primitive)

Unboxing: get(0).intValue() → the primitive 5. (A null element would throw a NullPointerException.)

names0"Ann"1"Tom"2"Bob"3nums•Integer: 5object on the heap5int x (primitive)

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 returns true; otherwise false.
  • 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

array0Java1Python2C++3Go

A list of 4 words.

array0Java1Python2C++3Goa: [0, ?)

spliterator(): index 0, fence −1 → the bound is set from size() on first use (lazily).

array0Java1Python2C++3Goa: [2, 4)b: [0, 2)

trySplit(): fence = 4, mid = (0 + 4) / 2 = 2. The first half [0, 2) goes to the new b; a keeps [2, 4).

array0Java1Python2C++3Goa: [2, 4)b: [1, 2)

b.tryAdvance: an element is left → "Java" goes to the action (println), index moves to 1; true.

array0Java1Python2C++3Goa: [2, 4)b: [2, 2)

b.tryAdvance: an element is left → "Python" goes to the action (println), index moves to 2; true.

array0Java1Python2C++3Goa: [2, 4)b: [2, 2)

b.tryAdvance: index = fence → nothing left, false; the loop ends.

array0Java1Python2C++3Goa: [3, 4)b: [2, 2)

a.tryAdvance: an element is left → "C++" goes to the action (println), index moves to 3; true.

array0Java1Python2C++3Goa: [4, 4)b: [2, 2)

a.tryAdvance: an element is left → "Go" goes to the action (println), index moves to 4; true.

array0Java1Python2C++3Goa: [4, 4)b: [2, 2)

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

1 · indexed for
int n = list.size();
for (int i = 0;
     i < n; i++) {
  String s =
      list.get(i);
  ...
}

Lists only; when you also need the index.

2 · forEach
list.forEach(
  System.out::println);

// or for-each:
for (String s : list) ...

Any Iterable; the shortest form.

3 · Iterator
Iterator<String> it =
    list.iterator();
while (it.hasNext()) {
  String s = it.next();
}

When you need to remove safely while traversing.

Careful: on a 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

ABCDEFfirstlast

A doubly linked list with 6 nodes.

ABCDEFfirstlast

steps counts how many links the get calls walk in total.

ABCDEFfirstlastx

get(0): 0 < n/2 = 3 → walks from first, 0 links. Total 0.

ABCDEFfirstlastx

get(1): 1 < n/2 = 3 → walks from first, 1 link. Total 1.

ABCDEFfirstlastx

get(2): 2 < n/2 = 3 → walks from first, 2 links. Total 3.

ABCDEFfirstlastx

get(3): 3 ≥ n/2 = 3 → walks from last, 2 links. Total 5.

ABCDEFfirstlastx

get(4): 4 ≥ n/2 = 3 → walks from last, 1 link. Total 6.

ABCDEFfirstlastx

get(5): 5 ≥ n/2 = 3 → walks from last, 0 links. Total 6.

ABCDEFfirstlast

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

hasNext()Are there elements left? false at the end.
next()Returns the next element and advances the cursor. With nothing left: NoSuchElementException.
remove()Removes the element returned by the last next() (an optional operation).
"Ann"0 "Tom"1 "Bob"2 cursor

iterator(): the cursor sits before the first element. hasNext() → true

"Ann"0 "Tom"1 "Bob"2 cursor

next() → "Ann" (the cursor jumps over the element)

"Ann"0 "Tom"1 "Bob"2 cursor

next() → "Tom"

"Ann"0 "Tom"1 "Bob"2 cursor

next() → "Bob"; now hasNext() → false and the loop ends

"Ann"0 "Tom"1 "Bob"2 cursor

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

list0"Ann"1"Tom"2"Bob"cursor

iterator(): the cursor sits before the first element (cursor = 0). The iterator is a separate object that walks the list.

list0"Ann"1"Tom"2"Bob"cursor

hasNext(): cursor 0 ≠ size 3 → true.

list0"Ann"1"Tom"2"Bob"cursor

next() → "Ann"; the cursor jumps over the element (cursor = 1).

list0"Ann"1"Tom"2"Bob"cursor

Prints Ann.

list0"Ann"1"Tom"2"Bob"cursor

hasNext(): cursor 1 ≠ size 3 → true.

list0"Ann"1"Tom"2"Bob"cursor

next() → "Tom"; the cursor jumps over the element (cursor = 2).

list0"Ann"1"Tom"2"Bob"cursor

Prints Tom.

list0"Ann"1"Tom"2"Bob"cursor

hasNext(): cursor 2 ≠ size 3 → true.

list0"Ann"1"Tom"2"Bob"cursor

next() → "Bob"; the cursor jumps over the element (cursor = 3).

list0"Ann"1"Tom"2"Bob"cursor

Prints Bob.

list0"Ann"1"Tom"2"Bob"cursor

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

Wrong
for (String s : names)
    if (s.startsWith("A"))
        names.remove(s);
// ConcurrentModification-
// Exception (fail-fast)
Right
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 per next(); otherwise IllegalStateException.

Traversal · Step through the code

Code Trace: ConcurrentModificationException

listmodCount = 0

An empty ArrayList. Every structural change (add/remove) increments the list's modCount.

list0"Ann"1"Ben"modCount = 2

Two add calls → modCount = 2.

list0"Ann"1"Ben"2"Alice"modCount = 3

modCount = 3. Now we trace the for-each loop as the compiler expands it.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

iterator(): cursor 0; the iterator records the current count as expectedModCount = 3.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

hasNext(): cursor 0 ≠ size 3 → true.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

next() first checks modCount == expectedModCount: 3 == 3 ✓ → "Ann", cursor = 1.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

"Ann" starts with A → true.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 3 ✗

names.remove(s) removes directly from the list → elements shift left, modCount = 4. The iterator doesn't know (expected is still 3).

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 3 ✗

hasNext(): cursor 1 ≠ size 2 → true. ("Ben" is now behind the cursor and would never be visited!)

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 3 ✗

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()

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

The same list [Ann, Ben, Alice], modCount = 3. Iterator: cursor = 0, lastRet = −1 (nothing returned yet).

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

hasNext(): cursor 0 ≠ size 3 → true.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

next(): 3 == 3 ✓ → "Ann"; cursor = 1, lastRet = 0.

list0"Ann"1"Ben"2"Alice"cursormodCount = 3 · expectedModCount = 3 ✓

Does "Ann" start with A? Yes.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

it.remove() removes the element at lastRet; cursor = 0 (the shifted element is not skipped), lastRet = −1, expectedModCount = modCount = 4.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

hasNext(): cursor 0 ≠ size 2 → true.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

next(): 4 == 4 ✓ → "Ben"; cursor = 1, lastRet = 0.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

Does "Ben" start with A? No.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

hasNext(): cursor 1 ≠ size 2 → true.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

next(): 4 == 4 ✓ → "Alice"; cursor = 2, lastRet = 1.

list0"Ben"1"Alice"cursormodCount = 4 · expectedModCount = 4 ✓

Does "Alice" start with A? Yes.

list0"Ben"cursormodCount = 5 · expectedModCount = 5 ✓

it.remove() removes the element at lastRet; cursor = 1 (the shifted element is not skipped), lastRet = −1, expectedModCount = modCount = 5.

list0"Ben"cursormodCount = 5 · expectedModCount = 5 ✓

hasNext(): cursor 1 = size 1 → false. The loop ends with no error.

list0"Ben"cursormodCount = 5 · expectedModCount = 5 ✓

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.

MethodWhat 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

list0"Ann"1"Tom"2"Bob"cursor[Ann, Tom, Bob]

listIterator(): the cursor is at the start; nextIndex = 0, previousIndex = −1. Orange: the last returned element (lastRet).

list0"Ann"1"Tom"2"Bob"cursor[Ann, Tom, Bob]

next() → "Ann"; the cursor moves forward, lastRet = 0.

list0"Ann"1"Tom"2"Bob"cursor[Ann, Tom, Bob]

next() → "Tom"; lastRet = 1.

list0"Ann"1"TOM"2"Bob"cursor[Ann, TOM, Bob]

set("TOM") replaces the element at lastRet ("Tom"); the cursor stays put.

list0"Ann"1"TOM"2"Alice"3"Bob"cursor[Ann, TOM, Alice, Bob]

add("Alice") inserts before the cursor, and the cursor moves past the new element (the next next still returns "Bob"); lastRet = −1.

list0"Ann"1"TOM"2"Alice"3"Bob"cursor[Ann, TOM, Alice, Bob]

previous() → "Alice", moving backward; the cursor steps back, lastRet = 2.

list0"Ann"1"TOM"2"Bob"cursor[Ann, TOM, Bob]

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

list0"Ann"1"Tom"2"Bob"cursor

listIterator(): the cursor is at the start.

list0"Ann"1"Tom"2"Bob"cursor

hasNext() → true (cursor 0 < 3).

list0"Ann"1"Tom"2"Bob"cursor

next() → "Ann", printed; the cursor moves forward.

list0"Ann"1"Tom"2"Bob"cursor

hasNext() → true (cursor 1 < 3).

list0"Ann"1"Tom"2"Bob"cursor

next() → "Tom", printed; the cursor moves forward.

list0"Ann"1"Tom"2"Bob"cursor

hasNext() → true (cursor 2 < 3).

list0"Ann"1"Tom"2"Bob"cursor

next() → "Bob", printed; the cursor moves forward.

list0"Ann"1"Tom"2"Bob"cursor

hasNext() → false: the cursor is at the end. The first loop ends; we continue with the same iterator.

list0"Ann"1"Tom"2"Bob"cursor

hasPrevious() → true (cursor 3 > 0).

list0"Ann"1"Tom"2"Bob"cursor

previous() → "Bob", printed; the cursor moves back.

list0"Ann"1"Tom"2"Bob"cursor

hasPrevious() → true (cursor 2 > 0).

list0"Ann"1"Tom"2"Bob"cursor

previous() → "Tom", printed; the cursor moves back.

list0"Ann"1"Tom"2"Bob"cursor

hasPrevious() → true (cursor 1 > 0).

list0"Ann"1"Tom"2"Bob"cursor

previous() → "Ann", printed; the cursor moves back.

list0"Ann"1"Tom"2"Bob"cursor

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

ArrayListA growable array. Fast indexed access; the default general-purpose choice.
LinkedListA doubly linked list. Fast insertion/removal at the ends; slow indexed access.
VectorAn older version of ArrayList whose methods are synchronized.
StackA stack that extends Vector: push, pop, peek (LIFO).
CopyOnWriteArrayListCopies on every write; suits lists read by many threads.
Arrays.asList()Turns an array into a fixed-size List view.

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

array0A1B2C3size = 3 · capacity = 4

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.

array0A1B2C3size = 3 · capacity = 4

add(D): size 3 == capacity 4? No.

array0A1B2C3Dsize = 4 · capacity = 4

data[3] = D, size = 4; returns true.

array0A1B2C3Dsize = 4 · capacity = 4

add(E): size 4 == capacity 4? Yes → the array is full.

array0A1B2C3Dsize = 4 · capacity = 4

newCap = 4 + 4 / 2 = 6: about 1.5 times (Java: old + old >> 1).

array0A1B2C3Dsize = 4 · capacity = 4copyABCDcapacity = 6

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.

array0A1B2C3D4E5size = 5 · capacity = 6

data[4] = E, size = 5; returns true.

array0A1B2C3D4E5size = 5 · capacity = 6

add(F): size 5 == capacity 6? No.

array0A1B2C3D4E5Fsize = 6 · capacity = 6

data[5] = F, size = 6; returns true.

array0A1B2C3D4E5Fsize = 6 · capacity = 6

add(G): size 6 == capacity 6? Yes → the array is full.

array0A1B2C3D4E5Fsize = 6 · capacity = 6

newCap = 6 + 6 / 2 = 9: about 1.5 times (Java: old + old >> 1).

array0A1B2C3D4E5Fsize = 6 · capacity = 6copyABCDEFcapacity = 9

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.

array0A1B2C3D4E5F6G78size = 7 · capacity = 9

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?

5010015020010203040number of elements added, ntotal elements copied+4 growth: 180×1.5: 79×2: 60
  • 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
OperationCost
get(i), set(i, e)O(1)
add(e) (at the end)amortized O(1)
add(i, e), remove(i)O(n)
contains, indexOfO(n)
size()O(1)
Pros over an arrayGrows on its own; adding, removing, searching, and sorting come as ready-made methods.
ConsHolds objects only (boxing costs); every access pays for a bounds check and a method call.

List Implementations · Step through the code

Code Trace: What ArrayList Operations Cost

empty array {}

An empty new ArrayList<>(): the internal array starts empty; the first add allocates one of capacity 10.

array0"Ann"123456… capacity 10

The first add creates an array of 10 and puts Ann at index 0. Appending needs no shifting.

array0"Ann"1"Dan"23456… capacity 10

Dan goes to index 1 (amortized O(1)).

array0"Ann"1"Dan"23456… capacity 10

add(0, …): first the 2 elements from index 0 on shift one place right (starting from the right).

array0"Ben"1"Ann"2"Dan"3456… capacity 10

Ben goes into the freed index 0. Inserting at the front costs n shifts → O(n).

array0"Ben"1"Ann"2"Dan"3456… capacity 10get(1)

get(1): direct access by address arithmetic → O(1), no shifting.

array0"Ben"1"Ann"2"Dan"3456… capacity 10

remove(0): Ben is about to go…

array0"Ann"1"Dan"23456… capacity 10

…the next 2 elements shift left and the last cell is set to null. The capacity does not shrink.

array0"Ann"1"Dan"23456… capacity 10

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)

0A1B2C3D45arraysize = 4

[A, B, C, D], capacity 6. add(1, "X"): X goes to index 1, so B, C, D must shift one place right.

0A1B2C3D45arraysize = 4

0 ≤ 1 ≤ size (4) → a valid index (otherwise IndexOutOfBoundsException).

0A1B2C3D45arraysize = 4

size 4 < capacity 6 → no need to grow.

0A1B2C3D4D5array▲ksize = 4

k = 4 > 1: data[4] = data[3] → D is copied right. We start from the right so nothing is overwritten.

0A1B2C3C4D5array▲ksize = 4

k = 3 > 1: data[3] = data[2] → C is copied right. We start from the right so nothing is overwritten.

0A1B2B3C4D5array▲ksize = 4

k = 2 > 1: data[2] = data[1] → B is copied right. We start from the right so nothing is overwritten.

0A1B2B3C4D5array▲ksize = 4

k = 1 > 1 is false → the loop ends. data[1] still holds the old copy of B.

0A1X2B3C4D5arraysize = 4

data[1] = X fills the gap.

0A1X2B3C4D5arraysize = 5

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)

0A1X2B3C4D5arraysize = 5

The list is [A, X, B, C, D]. remove(1): X goes, so B, C, D must shift left.

0A1X2B3C4D5arraysize = 5

0 ≤ 1 < size (5) → a valid index.

0A1X2B3C4D5arraysize = 5

old = data[1] = X (to be returned).

0A1B2B3C4D5array▲ksize = 5

k = 1 < 4: data[1] = data[2] → B shifts left. This time we start from the left.

0A1B2C3C4D5array▲ksize = 5

k = 2 < 4: data[2] = data[3] → C shifts left. This time we start from the left.

0A1B2C3D4D5array▲ksize = 5

k = 3 < 4: data[3] = data[4] → D shifts left. This time we start from the left.

0A1B2C3D4D5array▲ksize = 5

k = 4 < 4 is false → the loop ends. D now appears twice at the end.

0A1B2C3D45arraysize = 4

data[--size] = null: size 4; the extra reference is cleared (preventing a memory leak). The capacity does not shrink.

0A1B2C3D45arraysize = 4

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

"A" "B" "C" prevdatanext null null first last
  • 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 first and last.
  • Besides List, it implements Deque, 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
OperationCost
add / remove at either endO(1)
get(i), set(i, e)O(n)
add(i, e), remove(i)O(n)*
add / remove through an iteratorO(1)
* Relinking is O(1), but first we must walk to node i, which takes O(n). "Insertion is fast in a LinkedList" holds only when we already have the position (an end, or a ListIterator).

List Implementations · Step through the code

Code Trace: What LinkedList Operations Cost

first = null · last = null

An empty LinkedList: no nodes; first and last are null.

Bfirst, lastnull ←→ null

add = addLast: a single node, and both first and last point to it.

ABfirstlastnull ←→ null

addFirst: a new node; A.next = B, B.prev = A, first = A → O(1), no shifting.

ABCfirstlastnull ←→ null

addLast: thanks to last, no walk to the end is needed → O(1).

ABCfirstlastxnull ←→ null

get(1) → node(1): 1 < size/2 = 1 is false → start from the end: x = last (C).

ABCfirstlastxnull ←→ null

x = x.prev → B, the node we want, after walking 1 link. O(n) in general.

ABCfirstlastnull ←→ null

removeFirst: A is about to be unlinked.

BCfirstlastnull ←→ null

first = B, B.prev = null; nothing refers to A any more, so the garbage collector reclaims it → O(1).

BCfirstlastnull ←→ null

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)

first = null · last = null · size = 0

An empty LinkedList. addLast("A"), then addLast("B") (the same logic as Java's linkLast).

first = null · last = null · size = 0

l = last = null: remember the old last node.

Anfirst = null · last = null · size = 0

A new node: prev = l (null), next = null.

Alast, nfirst = null · size = 0

last = n.

Afirst, last, nsize = 0

l == null (the list was empty) → first = n: the only node is both first and last.

Afirst, lastsize = 1

size = 1.

Afirst, last, lsize = 1

l = last = node(A): remember the old last node.

ABfirst, last, lnsize = 1

A new node: prev = l (node(A)), next = null. The back link is set at construction.

ABfirst, llast, nsize = 1

last = n.

ABfirst, llast, nsize = 1

l is not null → else.

ABfirst, llast, nsize = 1

l.next = n: the forward link A → B.

ABfirstlastsize = 2

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)

ABCfirstlastsize = 3

[A, B, C]. remove(1): to find B, we first have to walk.

ABCfirstlastsize = 3

0 ≤ 1 < 3 → a valid index.

ABCfirst, xlastsize = 3

x = first (A). There is no direct indexed access as in an array.

ABCfirstlastxsize = 3

k = 0 < 1: x = x.next → B.

ABCfirstlastxsize = 3

k = 1 < 1 is false → the walk ends after i steps: O(i). (If i ≥ size/2, Java walks backward from last.)

ABCfirst, plast, sxsize = 3

p = x.prev = A, s = x.next = C: the two neighbors of the node to remove.

ABCfirst, plast, sxsize = 3

p is not null → p.next = s: A now points straight to C (B is bypassed).

ABCfirst, plast, sxsize = 3

s is not null → s.prev = p: C points back to A. B is cut off in both directions.

ABCfirstlastxsize = 2

size = 2.

ABCfirstlastxsize = 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

headerABCtrailerpsentinelsentinelafter(p) = position of C · before(p) = position of A
  • Indices shift on insertion and removal; a position stays with its element, like the cursor in a text editor.
  • Goodrich–Tamassia: Position<E> offers only getElement(); 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.
MethodCost
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)

headerACtrailerpsize = 2

header ⇄ A ⇄ C ⇄ trailer; p is the position of A. We call addAfter(p, "B").

headerACtrailernsize = 2

validate(p): is p a valid node of this list? Yes → it is cast to a Node.

headerACtrailerpredsuccsize = 2

The neighbors are known: pred = A, succ = A.next = C. The work is handed to addBetween.

headerACtrailerBpredsuccnewestsize = 2

The new node points to both neighbors, but nothing points to it yet.

headerACtrailerBpredsuccnewestsize = 2

pred.next = newest: forward, A → B → C.

headerACtrailerBpredsuccnewestsize = 2

succ.prev = newest: backward, C → B → A. The old A ⇄ C links are gone.

headerACtrailerBsize = 3

size++. No walking, no shifting: 4 assignments → O(1).

headerACtrailerBreturnedsize = 3

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?

ArrayListLinkedList
Internalsgrowable arraydoubly linked nodes
get(i)O(1)O(n)
Appendamortized O(1)O(1)
Add / remove at the frontO(n)O(1)
Memory per element1 reference (+ spare capacity)a node object (3 references)
Cache behaviorcontiguous, fastscattered, slow
Default: ArrayListFaster in most scenarios (read-heavy, appending at the end).
LinkedList / ArrayDequeWhen you add and remove at both ends often (queue, deque).

List Implementations

ArrayList and LinkedList in Memory

ArrayListArrayListsize = 3Object[]: contiguous references (+ spare capacity)ABCLinkedListABCone node object per element: data + prev + next; scattered in memory
ArrayList

About 1 reference per element (4–8 bytes) + spare capacity. The array is contiguous, so the CPU cache prefetches the next elements.

LinkedList

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);
}
Vector is a legacy class from Java 1.0. New code should use 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:

Thread T1Thread T2Vector v20size = 1

Start: v = [20]. Both threads will run if (!v.isEmpty()) v.remove(0);.

Thread T1Thread T2isEmpty() → falseVector v20size = 1

T1: isEmpty() takes the lock, returns false, and releases the lock.

Thread T1Thread T2isEmpty() → falseisEmpty() → falseVector v20size = 1

T2 slips in: v still has 1 element, so it sees false too. Both think they can remove.

Thread T1Thread T2isEmpty() → falseremove(0) → 20isEmpty() → falseVector vemptysize = 0

T1: remove(0) → 20. v is now empty.

Thread T1Thread T2isEmpty() → falseremove(0) → 20isEmpty() → falseremove(0) → ERRORVector vemptysize = 0

T2: remove(0) on an empty vector → ArrayIndexOutOfBoundsException. Each method is synchronized on its own, but the pair is not atomic.

Thread T1Thread T2synchronized (v) { isEmpty → false remove(0) → 20 }synchronized (v) { waits…Vector vemptysize = 0T1 holds the lock: T2 cannot enter

The fix: put the compound action under one lock with synchronized (v) { … }. T2 waits until T1 leaves the block.

Thread T1Thread T2synchronized (v) { isEmpty → false remove(0) → 20 }synchronized (v) { isEmpty → true} (no removal)Vector vemptysize = 0

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.

Because Stack extends Vector, it also carries methods that break LIFO, such as 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.
list a b c array A iterator

Readers read the internal array without locking; each iterator walks the array as it was when the iterator was created (a snapshot).

list a b c array A iterator a b c d array B (copy + new element) copy

add("d"): the writer takes the lock, copies the array, and appends the new element to the copy → O(n)

list a b c array A iterator a b c d array B (copy + new element) copy

The list reference switches to the new array. The old iterator keeps walking A: no ConcurrentModificationException.

Good forLists that are traversed often and rarely change: event listeners, configuration.
Bad forLarge lists that change often: every write copies the whole array. it.remove() is not supported.

List Implementations · Step through the code

Code Trace: CopyOnWriteArrayList add(e)

Aabc← list.array, iterator it (cursor 1)

The list points to A = [a, b, c]. An iterator has walked over A and read "a" (cursor 1). Now add("d").

Aabc← list.array, iterator it (cursor 1)lock: held by writer

Writers take the lock, so two writers cannot overwrite each other's copies. Readers never wait for the lock.

Aabc← list.array, old, iterator it (cursor 1)lock: held by writer

old = array: the current array, A.

Aabc← list.array, old, iterator it (cursor 1)lock: held by writer

n = 3.

AabcBabc← list.array, old, iterator it (cursor 1)← copylock: held by writer

Arrays.copyOf(old, 4): every element is copied into the copy array → O(n). A is left untouched.

AabcBabcd← list.array, old, iterator it (cursor 1)← copylock: held by writer

copy[3] = "d": the change happens only in the copy.

AabcBabcd← iterator it (cursor 1)← list.arraylock: held by writer

array = copy: a single reference assignment; the list now points to B. The iterator is still on A.

AabcBabcd← iterator it (cursor 1)← list.array

Returns true and releases the lock.

AabcBabcd← iterator it (cursor 3)← list.array

The iterator's it.next() → "b", then "c": it walks its snapshot (A), never sees "d", and throws no ConcurrentModificationException.

AabcBabcd← list.array, iterator it (cursor 0)

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 List interface; nothing is copied, and the array and the list share the same memory.
  • The list is fixed-size but not immutable: set works (and shows up in the array); add/remove do 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
setadd / removeLink 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

array0a1b2cString[] (a single array)

An array of 3 elements.

arraylist0a1b2cString[] (a single array)list: a view of the same array

Arrays.asList copies nothing: the returned list is a view wrapping the same array → O(1).

arraylist0x1b2cString[] (a single array)list: a view of the same array

list.set(0, "x") writes into the array: array[0] is x too.

arraylist0x1b2zString[] (a single array)list: a view of the same array

It works the other way too: writing to the array changes the list.

arraylist0x1b2zString[] (a single array)list: a view of the same array

If uncommented: the array's length cannot change, so add/remove → UnsupportedOperationException.

arraylistcopy0x1b2zString[] (a single array)list: a view of the same arrayxbzseparate array

For an independent, growable list, copy it: new ArrayList<>(list) allocates a new array.

arraylistcopy0x1b2zString[] (a single array)list: a view of the same arrayxbzdseparate array

Adding to the copy is fine; array and list are unaffected.

arraylistcopy0x1b2zString[] (a single array)list: a view of the same arrayxbzdseparate array

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

Classget(i)appendfront / middleThreads
ArrayListO(1)amortized O(1)O(n)not safe
LinkedListO(n)O(1)O(1) / O(n)not safe
VectorO(1)amortized O(1)O(n)synchronized
StackO(1)push O(1)—synchronized
CopyOnWriteArrayListO(1)O(n)O(n)safe (by copying)
Arrays.asListO(1)✗✗not safe
Traversalfor-each / Iterator is O(n) on every list. To remove while traversing, use it.remove() or removeIf.
Interactive simulatorList ADT operations, step by step: List ADT Simulator.

Summary

Sample Problems

  1. What is the list after List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); l.remove(1);?
  2. What does it cost to traverse a LinkedList with for (int i…) get(i)? What is better?
  3. What happens when we add an element to an ArrayList with capacity 10 that holds 10 elements?
  4. Why does Arrays.asList(array).add(x) fail? Why doesn't set?
  5. Which class suits a listener list that is read often, rarely changes, and is shared by many threads?
  6. On [A, B, C], after it = listIterator(); it.next(); it.add("X");, what are the list and it.next()?
Show answers
  1. [5, 7]: an int argument counts as an index (remove(int)).
  2. O(n²); with for-each or an Iterator, O(n).
  3. 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)).
  4. The list is backed by the array and has a fixed size; set doesn't change the size, it just writes into the array.
  5. CopyOnWriteArrayList.
  6. [A, X, B, C]; it.next() → "B" (add inserts before the cursor).

Summary

Exercises

  1. l = [A, B, C, D]; what is l after l.subList(1, 3).clear();? And what if we then call l.add("E") and read the old view?
  2. A dynamic array grows by 2 every time it fills up. How many copies do n adds make in total?
  3. Which contract would break if Range.next() skipped the k >= end check?
  4. Why is remove(p) O(1) in a positional list but LinkedList.remove(int) O(n)?
  5. l = new ArrayList<>(List.of(3, 1, 2)); l.remove(Integer.valueOf(1)); l.remove(1); → l?
Answers / hints
  1. [A, D]. Once l itself changes, the old view becomes invalid → ConcurrentModificationException.
  2. 2 + 4 + 6 + … ≈ n²/4 → O(n²) in total, O(n) per operation: fixed increments don't give amortized O(1).
  3. The contract to throw NoSuchElementException when no elements are left; it would return values outside the range.
  4. The position is the node itself (4 link assignments); removing by index first walks to node i.
  5. [3, 2]; then remove(1) removes by index → [3].

Summary

Further Reading

  • Oracle, Java SE 17 API documentation for Collection, List, Iterator, ListIterator, and Spliterator.
  • Bloch, Effective Java, 3rd ed., 2018.
  • Goodrich, Tamassia, and Goldwasser, Data Structures and Algorithms in Java, 6th ed., 2014.

The End

Chapter 6: The List ADT and Java Collections
Next deck: Chapter 7: Stacks · Study questions · Simulator: List ADT Simulator · Glossary
1 / 1 Sercan KÜLCÜ. All rights reserved.