Skip to lesson

Lists of your own objects

A List<Student> does not hold students; it holds references to Student objects. That one fact explains how searching, updating and sharing a list of your own objects really work.

A list stores references

A reference is a link to an object. A List<Student> does not hold the student objects themselves; each slot holds a reference to one. Copying a reference, or adding it to a list, never copies the object.

students.add(s) stores a reference to the object s points to. No copy is made, and students.get(0) gives back a reference to that same object.

Example 1 · A list of Student objects

ClassListDemo.javaJava
import java.util.ArrayList;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 String toString() {        return roll + " " + name + " (" + marks + ")";    }}
public class ClassListDemo {    public static void main(String[] args) {        List<Student> students = new ArrayList<>();        students.add(new Student("R101", "Aarav", 78));        students.add(new Student("R102", "Diya", 91));        students.add(new Student("R103", "Kabir", 66));        System.out.println(students);
        int total = 0;        Student topper = students.get(0);        for (Student s : students) {            total = total + s.getMarks();            if (s.getMarks() > topper.getMarks()) {                topper = s;            }        }        System.out.println("Average: " + (total / students.size()));        System.out.println("Topper: " + topper.getName());    }}
Output
[R101 Aarav (78), R102 Diya (91), R103 Kabir (66)]
Average: 78
Topper: Diya

What this code does

  • The list prints nicely because Student overrides toString().
  • In the loop, s is a reference to each student in turn, so s.getMarks() reads the real object.
  • topper is just another reference to one of the students in the list, not a copy.

So if you change an object through any reference, every list that holds it shows the change. Adding one object to two lists, or twice to one list, means two references to one object.

Printing a list calls toString() on each item. Override toString() in your class, or the list prints things like Student@1b6d3586.

contains, indexOf and remove need equals

contains, indexOf and remove(Object) compare items with equals. Without your own equals, only the very same object matches: a new Student with the same roll number is "not found".

Example 2 · Bug: the list cannot find an equal student

NoEqualsBugDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Student {    private final String roll;    private final String name;
    Student(String roll, String name) {        this.roll = roll;        this.name = name;    }
    @Override    public String toString() {        return roll + " " + name;    }}
public class NoEqualsBugDemo {    public static void main(String[] args) {        List<Student> hostel = new ArrayList<>();        hostel.add(new Student("R101", "Aarav"));        hostel.add(new Student("R102", "Diya"));
        Student diya = new Student("R102", "Diya");        System.out.println("Contains Diya? " + hostel.contains(diya));        System.out.println("Index of Diya: " + hostel.indexOf(diya));        System.out.println("Removed Diya? " + hostel.remove(diya));        System.out.println("Hostel: " + hostel);    }}
Output
Contains Diya? false
Index of Diya: -1
Removed Diya? false
Hostel: [R101 Aarav, R102 Diya]

What this code does

  • diya has the same roll and name, but it is a different object. Without an equals override, Object.equals only matches the same object.
  • So contains is false, indexOf is -1 and remove removes nothing. No error; just wrong answers.

Example 3 · Fix: override equals and hashCode on the roll number

EqualsFixDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Student {    private final String roll;    private final String name;
    Student(String roll, String name) {        this.roll = roll;        this.name = name;    }
    @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;    }}
record Book(String isbn, String title) {}
public class EqualsFixDemo {    public static void main(String[] args) {        List<Student> hostel = new ArrayList<>();        hostel.add(new Student("R101", "Aarav"));        hostel.add(new Student("R102", "Diya"));
        Student diya = new Student("R102", "Diya");        System.out.println("Contains Diya? " + hostel.contains(diya));        System.out.println("Index of Diya: " + hostel.indexOf(diya));        System.out.println("Removed Diya? " + hostel.remove(diya));        System.out.println("Hostel: " + hostel);
        List<Book> shelf = new ArrayList<>();        shelf.add(new Book("978-1", "Java Basics"));        System.out.println("Has the book? " + shelf.contains(new Book("978-1", "Java Basics")));        System.out.println("Other title? " + shelf.contains(new Book("978-1", "Java Basic")));    }}
Output
Contains Diya? true
Index of Diya: 1
Removed Diya? true
Hostel: [R101 Aarav]
Has the book? true
Other title? false

What this code does

  • Now two students with the same roll number are equal, so all three methods find Diya.
  • hashCode uses the same field as equals, which keeps the contract for sets and maps later.
  • The record gets equals from all its fields: the same ISBN with a different title is not equal.

equals comes from Object and works like == until you override it. Override equals to say what makes two objects the same, usually an id such as a roll number. Override hashCode with it, as the equals/hashCode contract from the OOP section says. A list does not use hashCode, but HashSet and HashMap do (Sets and Maps modules), and your class will end up there.

A record gets equals and hashCode for free, built from all its components. Two records match only if every field matches.

Find the bug

Find the equals bug

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

Two students are the same when the roll numbers match.

Round 1 of 3

Find and update an object

To find an object by one field, such as a roll number, loop over the list and compare that field. Return the object, or null when nothing matches, and check for null before you use the result.

Example 4 · Find a student and update marks

UpdateInListDemo.javaJava
import java.util.ArrayList;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;    }
    int getMarks() {        return marks;    }
    void setMarks(int marks) {        this.marks = marks;    }
    @Override    public String toString() {        return name + "=" + marks;    }}
public class UpdateInListDemo {    static Student findByRoll(List<Student> list, String roll) {        for (Student s : list) {            if (s.getRoll().equals(roll)) {                return s;            }        }        return null;    }
    public static void main(String[] args) {        List<Student> all = new ArrayList<>();        all.add(new Student("R101", "Aarav", 78));        all.add(new Student("R102", "Diya", 91));        all.add(new Student("R103", "Kabir", 66));
        List<Student> toppers = new ArrayList<>();        toppers.add(all.get(1));
        Student found = findByRoll(all, "R102");        if (found != null) {            found.setMarks(95);        }        System.out.println("All: " + all);        System.out.println("Toppers: " + toppers);
        for (Student s : all) {            if (s.getMarks() < 70) {                s.setMarks(s.getMarks() + 5);            }        }        System.out.println("After grace marks: " + all);        System.out.println("R109: " + findByRoll(all, "R109"));    }}
Output
All: [Aarav=78, Diya=95, Kabir=66]
Toppers: [Diya=95]
After grace marks: [Aarav=78, Diya=95, Kabir=71]
R109: null

What this code does

  • all and toppers both hold a reference to Diya's one object, so setting 95 shows up in both lists.
  • Calling setters inside a for-each loop is safe: the objects change, but the list itself (its size and slots) does not.
  • findByRoll returns null for a missing roll, which is why the caller checks before using the result.

To update a mutable object, call its setter on the object you found. The list holds the same object, so it sees the change at once. Calling setters inside a for-each loop is fine: you change objects, not the list.

An immutable object, such as a record, cannot change. Build a new object and put it in with set(index, newObject).

Do not leak your list: defensive copies

A defensive copy is a copy of a list that a class hands out or takes in, so outside code cannot change the class's own data. List.copyOf(list) and new ArrayList<>(list) make one.

If a class returns its private list field from a getter, any caller can add, remove or clear it, and skip every rule your class checks. Encapsulation is broken.

Example 5 · Bug: a getter that leaks the list

LeakyGetterDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Classroom {    private static final int SEATS = 3;    private final List<String> students = new ArrayList<>();
    boolean admit(String name) {        if (students.size() >= SEATS) {            System.out.println("No seat for " + name);            return false;        }        students.add(name);        return true;    }
    List<String> getStudents() {        return students;    }}
public class LeakyGetterDemo {    public static void main(String[] args) {        Classroom room = new Classroom();        room.admit("Aarav");        room.admit("Diya");        room.admit("Kabir");        room.admit("Meera");
        room.getStudents().add("Meera");        room.getStudents().remove("Aarav");        System.out.println("Inside the class: " + room.getStudents());    }}
Output
No seat for Meera
Inside the class: [Diya, Kabir, Meera]

What this code does

  • admit refuses a fourth student, but the getter hands out the real private list.
  • Outside code adds Meera and removes Aarav directly, skipping the seat rule. The class can no longer protect its own data.

Example 6 · Fix: return a defensive copy with List.copyOf

DefensiveCopyDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Classroom {    private static final int SEATS = 3;    private final List<String> students = new ArrayList<>();
    boolean admit(String name) {        if (students.size() >= SEATS) {            System.out.println("No seat for " + name);            return false;        }        students.add(name);        return true;    }
    List<String> getStudents() {        return List.copyOf(students);    }}
public class DefensiveCopyDemo {    public static void main(String[] args) {        Classroom room = new Classroom();        room.admit("Aarav");        room.admit("Diya");
        List<String> snapshot = room.getStudents();        try {            snapshot.add("Meera");        } catch (UnsupportedOperationException e) {            System.out.println("Cannot change the copy: " + e.getClass().getSimpleName());        }
        room.admit("Kabir");        room.admit("Meera");        System.out.println("Old snapshot: " + snapshot);        System.out.println("Inside the class: " + room.getStudents());
        List<String> myCopy = new ArrayList<>(room.getStudents());        myCopy.add("Guest");        System.out.println("My own copy: " + myCopy);        System.out.println("Still inside: " + room.getStudents());    }}
Output
Cannot change the copy: UnsupportedOperationException
No seat for Meera
Old snapshot: [Aarav, Diya]
Inside the class: [Aarav, Diya, Kabir]
My own copy: [Aarav, Diya, Kabir, Guest]
Still inside: [Aarav, Diya, Kabir]

What this code does

  • List.copyOf returns a read-only copy, so add on it throws UnsupportedOperationException and the seat rule holds.
  • A copy is a snapshot: the old one does not show Kabir, who was admitted later. Call the getter again for fresh data.
  • A caller who needs a list to change wraps it in new ArrayList<>(...); that copy is theirs alone.

Return a defensive copy instead. List.copyOf(students) gives a read-only copy: calling add on it throws UnsupportedOperationException. new ArrayList<>(students) gives a separate copy the caller may change freely without touching yours. When a constructor receives a list, copy it in the same way.

Both copies are shallow: the new list holds references to the same objects. A caller can still call a setter on a student it got from the copy. Immutable elements, such as records, close that gap.

The Fixed and unmodifiable lists lesson compares List.copyOf, List.of and other read-only lists in detail.

Next step

Check your understanding

12 quick questions