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.
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 outTo 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<>()ornew ArrayList<>(List.of(...)) - Fixed values →
List.of(...) - Give out without allowing changes →
List.copyOf(list)orCollections.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:
- Which type?
ArrayListunless there is a real reason for another. - Does the element class have
equals,hashCodeandtoString? - Will I remove while looping? Then
removeIfor anIterator. - Are my indexes between
0andsize() - 1? - Do I need the original order? Then sort a copy.
- 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
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); }}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
nchanges only the loop variable, so the names stay lower case.
Example 2 · The same program, fixed
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); }}Absent: [3, 8, 15] Eligible: [80, 92] Names: [ASHA, RAVI]
What this code does
Integer.valueOf(2)makes Java callremove(Object), so the value 2 is removed wherever it sits.removeIfchecks every item exactly once, so both 60 and 70 are removed.replaceAllstores each new value back into the list.
The silent bugs, each with the lesson to review:
list.remove(1)on aList<Integer>removes index 1 → useremove(Integer.valueOf(1)). Review: ArrayList: add, get, set, remove (opens in a new tab)- Removing in a forward index loop skips the next item → use
removeIf, anIterator, or loop backwards. Review: Iterator and safe removal (opens in a new tab) contains,indexOforremovecannot find your object → overrideequals(andhashCode), or use a record. Review: Lists of your own objects (opens in a new tab)binarySearchon an unsorted list says "missing" → sort first. Review: Search and sort a list (opens in a new tab)
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
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()); } }}1. IndexOutOfBoundsException: Index 2 out of bounds for length 2 2. ConcurrentModificationException 3. UnsupportedOperationException 4. NoSuchElementException 5. NullPointerException
What this code does
- Each
trytriggers one exception on purpose, so you can match the name to its cause: bad index, change during for-each, unmodifiable list, emptyLinkedList, unboxing anullInteger. - In real code, prevent them instead: check the index, use
removeIf, copy into anArrayList, checkisEmpty(), and keepnullout of lists.
The five exceptions and their causes:
IndexOutOfBoundsException→ index below 0 or not belowsize()ConcurrentModificationException→ list changed directly during a for-each or iterator loopUnsupportedOperationException→ change on aList.of,List.copyOf, unmodifiable orArrays.asListlistNoSuchElementException→getFirstornext()with nothing leftNullPointerException→nullinList.of, or unboxing anullInteger
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 4Trace 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.
Variables
- ids
- [10, 20, 30, 20]
- size
- 4
Output
(nothing printed yet)Line 6The list starts with four ids. The id 20 appears twice.
Example 4 · A complete marks register
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"); } }}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
equalson the roll number letscontainsrefuse a duplicate roll, even with a different name.findreturns the real object, sosetMarks(70)updates Meera inside the register;removeIfdrops Diya safely.- Marks are sorted in a separate list, so the register keeps its own order, and
List.copyOfstops outside code from clearing it.
Finish up
Mark complete & continue
Next: Must-do problems: Lists