Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most list bugs do not crash. They compile, run and quietly give a wrong answer: the wrong item removed, one item skipped, a student "not found". Knowing the few classic mistakes, and the five exceptions lists throw, fixes almost all of them.

Choosing and creating a list

Declare the interface and pick the class: List<String> names = new ArrayList<>();. ArrayList is the default for almost every job. Use a LinkedList only for a measured need, and List.of for a fixed group of values that must never change.

Java
List<String> names = new ArrayList<>();                         // changeable, emptyList<String> batch = new ArrayList<>(List.of("Asha", "Ravi"));  // changeable, with valuesList<String> days = List.of("Mon", "Wed", "Fri");               // fixed, never changesList<String> shared = List.copyOf(batch);                       // read-only copy to hand out

To start with values and still change the list later, copy them into an ArrayList. When you hand your list to other code, decide whether they may change it.

  • Changeable list → new ArrayList<>() or new ArrayList<>(List.of(...))
  • Fixed values → List.of(...)
  • Give out without allowing changes → List.copyOf(list) or Collections.unmodifiableList(list)
  • Work only at the ends (queue, stack) → ArrayDeque, in the Queues module

Before you write list code, run through these questions once, and most list bugs never get written:

  1. Which type? ArrayList unless there is a real reason for another.
  2. Does the element class have equals, hashCode and toString?
  3. Will I remove while looping? Then removeIf or an Iterator.
  4. Are my indexes between 0 and size() - 1?
  5. Do I need the original order? Then sort a copy.
  6. Am I returning a list field? Then return a copy or a read-only view.

Bugs that compile and run

These mistakes give no error at all, so learn to see them while reading code. Each one comes from a rule taught in this module.

Example 1 · Find the bugs: an attendance program

AttendanceBugsDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class AttendanceBugsDemo {    public static void main(String[] args) {        List<Integer> absentRolls = new ArrayList<>(List.of(3, 8, 15, 2));        // Roll 2 came late: take roll 2 off the absent list        absentRolls.remove(2);        System.out.println("Absent: " + absentRolls);
        List<Integer> attendance = new ArrayList<>(List.of(80, 60, 70, 92));        // Remove everyone below 75%        for (int i = 0; i < attendance.size(); i++) {            if (attendance.get(i) < 75) {                attendance.remove(i);            }        }        System.out.println("Eligible: " + attendance);
        List<String> names = new ArrayList<>(List.of("asha", "ravi"));        // Capitalise every name        for (String n : names) {            n = n.toUpperCase();        }        System.out.println("Names: " + names);    }}
Output
Absent: [3, 8, 2]
Eligible: [80, 70, 92]
Names: [asha, ravi]

What this code does

  • remove(2) removes index 2, which is roll 15. Roll 15 is wrongly marked present and roll 2 is still absent.
  • The forward loop removes 60, then 70 slides into index 1 and is skipped, so 70% counts as eligible.
  • Assigning to n changes only the loop variable, so the names stay lower case.

Example 2 · The same program, fixed

AttendanceFixedDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class AttendanceFixedDemo {    public static void main(String[] args) {        List<Integer> absentRolls = new ArrayList<>(List.of(3, 8, 15, 2));        absentRolls.remove(Integer.valueOf(2));        System.out.println("Absent: " + absentRolls);
        List<Integer> attendance = new ArrayList<>(List.of(80, 60, 70, 92));        attendance.removeIf(a -> a < 75);        System.out.println("Eligible: " + attendance);
        List<String> names = new ArrayList<>(List.of("asha", "ravi"));        names.replaceAll(n -> n.toUpperCase());        System.out.println("Names: " + names);    }}
Output
Absent: [3, 8, 15]
Eligible: [80, 92]
Names: [ASHA, RAVI]

What this code does

  • Integer.valueOf(2) makes Java call remove(Object), so the value 2 is removed wherever it sits.
  • removeIf checks every item exactly once, so both 60 and 70 are removed.
  • replaceAll stores each new value back into the list.

The silent bugs, each with the lesson to review:

Two more: changing the loop variable in for-each (m = m + 5) does not change the list (Looping through a list (opens in a new tab)), and Arrays.asList writes through to its array (Fixed and unmodifiable lists (opens in a new tab)).

The five exceptions lists throw

When a list does crash, the exception name tells you the cause. Read the first line of the trace for the name and message, and the last line that names your file for the place.

Example 3 · The five exceptions in one run

ListExceptionsTour.javaJava
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;
public class ListExceptionsTour {    public static void main(String[] args) {        List<String> names = new ArrayList<>(List.of("Om", "Ira"));
        try {            names.get(2);        } catch (IndexOutOfBoundsException e) {            System.out.println("1. " + e.getClass().getSimpleName() + ": " + e.getMessage());        }
        try {            for (String n : names) {                names.add(n + "!");            }        } catch (RuntimeException e) {            System.out.println("2. " + e.getClass().getSimpleName());        }
        try {            List.of("Om").add("Ira");        } catch (UnsupportedOperationException e) {            System.out.println("3. " + e.getClass().getSimpleName());        }
        try {            new LinkedList<String>().getFirst();        } catch (RuntimeException e) {            System.out.println("4. " + e.getClass().getSimpleName());        }
        try {            List<Integer> marks = new ArrayList<>();            marks.add(null);            int first = marks.get(0);        } catch (NullPointerException e) {            System.out.println("5. " + e.getClass().getSimpleName());        }    }}
Output
1. IndexOutOfBoundsException: Index 2 out of bounds for length 2
2. ConcurrentModificationException
3. UnsupportedOperationException
4. NoSuchElementException
5. NullPointerException

What this code does

  • Each try triggers one exception on purpose, so you can match the name to its cause: bad index, change during for-each, unmodifiable list, empty LinkedList, unboxing a null Integer.
  • In real code, prevent them instead: check the index, use removeIf, copy into an ArrayList, check isEmpty(), and keep null out of lists.

The five exceptions and their causes:

  • IndexOutOfBoundsException → index below 0 or not below size()
  • ConcurrentModificationException → list changed directly during a for-each or iterator loop
  • UnsupportedOperationException → change on a List.of, List.copyOf, unmodifiable or Arrays.asList list
  • NoSuchElementException → getFirst or next() with nothing left
  • NullPointerException → null in List.of, or unboxing a null Integer

None of these are checked exceptions, so the compiler never warns you. Prevent them with checks (isEmpty(), size()) and with the right tool, rather than by catching them.

Spot the bug

Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: is this an index or a value, does the loop remove, who may change the list, is it sorted?

Find the bug

Find the list bug

Each snippet should work. Tap the wrong line, then check the fix.

Remove the order with id 7 from the list of ids.

Round 1 of 4

Trace before you guess

When list calls change a list one after another, write the list down after every call. This program mixes remove(int), remove(Object) and add(index, item) on one list of ids.

Trace the code

Trace the list of ids

Step through and watch the list change after every call.

import java.util.ArrayList;
import java.util.List;
public class TraceLists {
public static void main(String[] args) {
List<Integer> ids = new ArrayList<>(List.of(10, 20, 30, 20));
ids.remove(1);
ids.remove(Integer.valueOf(20));
ids.add(0, 5);
System.out.println(ids + " " + ids.size());
}
}

Variables

ids
[10, 20, 30, 20]
size
4

Output

(nothing printed yet)

Line 6The list starts with four ids. The id 20 appears twice.

Step 1 of 5

Example 4 · A complete marks register

MarksRegisterDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Student {    private final String roll;    private final String name;    private int marks;
    Student(String roll, String name, int marks) {        this.roll = roll;        this.name = name;        this.marks = marks;    }
    String getRoll() {        return roll;    }
    String getName() {        return name;    }
    int getMarks() {        return marks;    }
    void setMarks(int marks) {        this.marks = marks;    }
    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (!(o instanceof Student other)) {            return false;        }        return roll.equals(other.roll);    }
    @Override    public int hashCode() {        return roll.hashCode();    }
    @Override    public String toString() {        return roll + " " + name + " " + marks;    }}
class MarksRegister {    private final List<Student> students = new ArrayList<>();
    boolean add(Student s) {        if (students.contains(s)) {            System.out.println("Duplicate roll " + s.getRoll() + " refused");            return false;        }        students.add(s);        return true;    }
    Student find(String roll) {        for (Student s : students) {            if (s.getRoll().equals(roll)) {                return s;            }        }        return null;    }
    int removeFailed(int passMark) {        int before = students.size();        students.removeIf(s -> s.getMarks() < passMark);        return before - students.size();    }
    List<Integer> marksHighToLow() {        List<Integer> marks = new ArrayList<>();        for (Student s : students) {            marks.add(s.getMarks());        }        Collections.sort(marks);        Collections.reverse(marks);        return marks;    }
    List<Student> getStudents() {        return List.copyOf(students);    }}
public class MarksRegisterDemo {    public static void main(String[] args) {        MarksRegister register = new MarksRegister();        register.add(new Student("R1", "Aarav", 78));        register.add(new Student("R2", "Diya", 31));        register.add(new Student("R3", "Kabir", 88));        register.add(new Student("R4", "Meera", 64));        register.add(new Student("R2", "Someone", 99));
        Student meera = register.find("R4");        if (meera != null) {            meera.setMarks(70);        }
        System.out.println("Removed (below 35): " + register.removeFailed(35));        System.out.println("Marks high to low: " + register.marksHighToLow());        for (Student s : register.getStudents()) {            System.out.println(s);        }
        try {            register.getStudents().clear();        } catch (UnsupportedOperationException e) {            System.out.println("Outside code cannot clear the register");        }    }}
Output
Duplicate roll R2 refused
Removed (below 35): 1
Marks high to low: [88, 78, 70]
R1 Aarav 78
R3 Kabir 88
R4 Meera 70
Outside code cannot clear the register

What this code does

  • equals on the roll number lets contains refuse a duplicate roll, even with a different name.
  • find returns the real object, so setMarks(70) updates Meera inside the register; removeIf drops Diya safely.
  • Marks are sorted in a separate list, so the register keeps its own order, and List.copyOf stops outside code from clearing it.

Finish up

Mark complete & continue

Next: Must-do problems: Lists