Skip to content

Module 9 · Collections and Generics — topic 2 of 5

Lists and Iterators

ArrayList in depth: adding, inserting, removing, searching and sublists, iterating safely with Iterator and removeIf, ListIterator, and ArrayList versus LinkedList.

Beginner 15 min read·Lesson 31 of 39 in Java Programming

Learning objectives

  • Use the main List operations correctly
  • Remove elements while iterating without ConcurrentModificationException
  • Compare ArrayList and LinkedList performance

Definition

A List is an ordered collection that allows duplicates and gives positional access by index. An Iterator is an object that traverses a collection one element at a time and can safely remove the current element.

Introduction

ArrayList is the collection you will use most often. It works like an array that grows automatically, and it adds dozens of useful operations. The one trap to learn early is modifying a list while looping over it.

Why it matters

Lists are the standard way to hold ordered data: rows from a database, items in a cart, lines from a file.

ConcurrentModificationException is one of the first runtime errors every Java developer meets.

Detailed explanation

Adding. add(e) appends; add(i, e) inserts at index i, shifting later elements right; addAll adds a whole collection.

Reading and changing. get(i), set(i, e) (returns the old element), size(), isEmpty(), indexOf(e), lastIndexOf(e) and contains(e) (which use equals).

Removing. remove(int index) removes by position; remove(Object o) removes the first equal element. On a List<Integer>, remove(1) removes index 1 — use remove(Integer.valueOf(1)) to remove the value. clear() empties the list.

Iterating. A for-each loop uses an Iterator behind the scenes. If you change the list's size during the loop (other than through the iterator), the next step throws ConcurrentModificationException. To remove while iterating, call iterator.remove() or, more simply, list.removeIf(condition).

ListIterator can move both ways and set or add elements during iteration. subList(from, to) returns a *view* of part of the list; changes to it affect the original.

ArrayList vs LinkedList. ArrayList: O(1) get and amortised O(1) add at the end, O(n) insert/remove in the middle. LinkedList: O(1) add/remove at the ends or at an iterator's position but O(n) get(i), more memory per element and poor cache behaviour. In practice ArrayList (or ArrayDeque for queues) wins almost always.

Syntax

Java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.add("d"); list.add(1, "x");
list.set(0, "A"); list.remove("b");
list.removeIf(s -> s.equals("x"));
Iterator<String> it = list.iterator();
while (it.hasNext()) if (it.next().isEmpty()) it.remove();
  • Indexes run from 0 to size() - 1.
  • remove(int) and remove(Object) are different overloads.
  • subList returns a view, not a copy.

Code examples

Everyday list operations

Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> cart = new ArrayList<>();
cart.add("milk");
cart.add("bread");
cart.add("eggs");
cart.add(1, "butter");
System.out.println(cart + " size " + cart.size());
String old = cart.set(0, "almond milk");
System.out.println("replaced " + old + ": " + cart);
cart.remove("bread");
System.out.println(cart + " contains eggs? " + cart.contains("eggs") + ", index of eggs: " + cart.indexOf("eggs"));
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30, 1));
nums.remove(1); // index 1
nums.remove(Integer.valueOf(1)); // the value 1
System.out.println(nums);
}
}
Output
[milk, butter, bread, eggs] size 4
replaced milk: [almond milk, butter, bread, eggs]
[almond milk, butter, eggs] contains eggs? true, index of eggs: 2
[10, 30]

Removing while iterating

Java
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>(List.of(45, 12, 78, 33, 90, 8));
try {
for (Integer m : marks) if (m < 40) marks.remove(m);
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException!");
}
List<Integer> a = new ArrayList<>(List.of(45, 12, 78, 33, 90, 8));
Iterator<Integer> it = a.iterator();
while (it.hasNext()) if (it.next() < 40) it.remove();
List<Integer> b = new ArrayList<>(List.of(45, 12, 78, 33, 90, 8));
b.removeIf(m -> m < 40);
System.out.println(a + " " + b);
}
}
Output
ConcurrentModificationException!
[45, 78, 90] [45, 78, 90]

More examples

ListIterator, subList views and sorting

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("asha", "ravi", "meera", "john", "priya"));
ListIterator<String> li = names.listIterator();
while (li.hasNext()) {
String n = li.next();
li.set(Character.toUpperCase(n.charAt(0)) + n.substring(1)); // capitalise in place
if (n.equals("meera")) li.add("Kiran"); // insert after Meera
}
System.out.println(names);
List<String> firstThree = names.subList(0, 3);
Collections.sort(firstThree); // sorts part of the original list
System.out.println(names);
firstThree.clear(); // removes them from the original
System.out.println(names);
List<Integer> scores = new ArrayList<>(List.of(70, 95, 82, 95, 60));
scores.sort(Comparator.reverseOrder());
System.out.println("top 3: " + scores.subList(0, 3) + ", replaced all: " + replaceAll(scores));
}
static List<Integer> replaceAll(List<Integer> list) {
List<Integer> copy = new ArrayList<>(list);
copy.replaceAll(x -> Math.min(x + 5, 100));
return copy;
}
}
Output
[Asha, Ravi, Meera, Kiran, John, Priya]
[Asha, Meera, Ravi, Kiran, John, Priya]
[Kiran, John, Priya]
top 3: [95, 95, 82], replaced all: [100, 100, 87, 75, 65]

Step-by-step explanation

  • listIterator() returns a ListIterator, which can replace the current element with set and insert after it with add during the loop.
  • Adding through the iterator is allowed, unlike calling names.add inside a for-each loop.
  • subList(0, 3) is a view of the first three elements; sorting it reorders those positions in the original list.
  • Clearing the view removes those three elements from the original list.
  • replaceAll applies a function to every element; working on a copy leaves scores unchanged.

Expected output

Running “ListIterator, subList views and sorting” prints exactly:

TextOutput
[Asha, Ravi, Meera, Kiran, John, Priya]
[Asha, Meera, Ravi, Kiran, John, Priya]
[Kiran, John, Priya]
top 3: [95, 95, 82], replaced all: [100, 100, 87, 75, 65]

Practical applications

  • Shopping carts, playlists and to-do lists
  • Results of database queries mapped to objects
  • Filtering out invalid records before processing

Best practices

  • Use ArrayList unless you have measured a reason not to.
  • Use removeIf, replaceAll and sort instead of manual index loops.
  • Be careful with remove on List<Integer>: pass Integer.valueOf for values.

Common mistakes

Modifying a list in a for-each loop

Avoid

for (String s : list) if (s.isBlank()) list.remove(s);

Prefer

list.removeIf(String::isBlank);

Structural changes during a for-each loop throw ConcurrentModificationException; removeIf or iterator.remove are safe.

Calling get(i) in a loop on a LinkedList

Avoid

for (int i = 0; i < linked.size(); i++) total += linked.get(i);

Prefer

for (int x : linked) total += x;

Each get(i) on a LinkedList walks from an end, turning the loop into O(n²).

Important notes

  • Arrays.asList returns a fixed-size list backed by the array: set works, add and remove throw.
  • ArrayList's capacity grows by about 50% when full; new ArrayList<>(expectedSize) avoids repeated growth.

Key takeaways

  • List keeps order, allows duplicates and gives index access.
  • Remove while iterating with iterator.remove() or removeIf.
  • ArrayList is the default; LinkedList is rarely faster.

Try it yourself

  1. 1
    Rotate a list right by k positions using subList and addAll.
  2. 2
    Merge two sorted ArrayLists into a new sorted list in one pass.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic