Lists of your own objects
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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()); }}[R101 Aarav (78), R102 Diya (91), R103 Kabir (66)] Average: 78 Topper: Diya
What this code does
- The list prints nicely because
StudentoverridestoString(). - In the loop,
sis a reference to each student in turn, sos.getMarks()reads the real object. topperis 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
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); }}Contains Diya? false Index of Diya: -1 Removed Diya? false Hostel: [R101 Aarav, R102 Diya]
What this code does
diyahas the same roll and name, but it is a different object. Without anequalsoverride,Object.equalsonly matches the same object.- So
containsisfalse,indexOfis-1andremoveremoves nothing. No error; just wrong answers.
Example 3 · Fix: override equals and hashCode on the roll number
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"))); }}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.
hashCodeuses the same field asequals, which keeps the contract for sets and maps later.- The record gets
equalsfrom 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 3Find 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
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")); }}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
allandtoppersboth 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.
findByRollreturnsnullfor 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
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()); }}No seat for Meera Inside the class: [Diya, Kabir, Meera]
What this code does
admitrefuses 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
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()); }}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.copyOfreturns a read-only copy, soaddon it throwsUnsupportedOperationExceptionand 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.
List.copyOf, List.of and other read-only lists in detail.Next step
Check your understanding
12 quick questions