Sets of your own objects
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A HashSet of your own objects drops duplicates only if your class overrides both equals and hashCode. Forget one of them and the set happily stores the same student twice.
How a HashSet compares objects
A bucket is a small group of stored values that share one place in a HashSet. hashCode() picks the bucket; equals is then used only on the values inside it.
When you call set.add(x) or set.contains(x), the set works in two steps. First it calls x.hashCode() to pick a bucket. Then it compares x with equals only against the objects in that bucket. The code below adds two equal students.
Example 1 · Bug: no equals or hashCode
import java.util.HashSet;import java.util.Set;
class Student { private final int roll; private final String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
@Override public String toString() { return roll + "-" + name; }}
public class NoEqualsDemo { public static void main(String[] args) { Set<Student> registered = new HashSet<>(); Student priya = new Student(101, "Priya");
registered.add(priya); registered.add(priya); System.out.println("Same object twice: " + registered.size());
registered.add(new Student(101, "Priya")); System.out.println("Equal-looking copy: " + registered.size()); System.out.println("Contains 101-Priya? " + registered.contains(new Student(101, "Priya"))); }}Same object twice: 1 Equal-looking copy: 2 Contains 101-Priya? false
What this code does
- Adding the very same object twice keeps the size at 1:
Object.equalsis==, and==istruefor one object. - A second object with the same fields counts as a new value, and
containswith a fresh copy finds nothing.
The versions from Object look at identity, not at the fields. equals means ==, and hashCode is a number tied to that one object. So two separate new Student(101, "Priya") objects are different to a set, even though every field matches.
That is fine for some classes. But for a student, a train seat or a coupon code, two objects with the same key data should count as one value. To see how equals and hashCode are written, read the hashCode method (opens in a new tab).
The classic duplicate bug
Many developers override equals and forget hashCode. An ArrayList still works, because list.contains uses only equals. A HashSet breaks. The code below shows it.
Example 2 · Bug: equals without hashCode
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
class Student { private final int roll; private final String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Student other && roll == other.roll; }}
public class HalfFixDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student(101, "Priya")); System.out.println("List contains? " + list.contains(new Student(101, "Priya")));
Set<Student> set = new HashSet<>(); set.add(new Student(101, "Priya")); set.add(new Student(101, "Priya")); System.out.println("Set size: " + set.size()); System.out.println("Set contains? " + set.contains(new Student(101, "Priya"))); }}List contains? true Set size: 2 Set contains? false
What this code does
- The list only calls
equals, so it works. The set first useshashCode, which is stillObject's version and differs for each object. - Different hash codes send the two students to different buckets, so
equalsis never called.o instanceof Student other && ...checks the type and compares in one line.
The reason is the first step. The two equal objects still have different hash codes from Object, so they go to different buckets. The set never even calls your equals, and it stores both.
This is why the equals–hashCode contract says: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). The other way round is not required: two different objects may share a hash code. That is called a collision, and equals sorts it out.
Find the bug
Find the set bug
Select the line that is wrong.
Two students with the same roll number must count once in a HashSet.
Round 1 of 3Writing equals and hashCode for a set
Key fields are the fields that decide when two objects are the same value. equals and hashCode must use exactly the same key fields, so equal objects always get the same hash code.
First decide which fields make two objects "the same": for a student, often the roll number alone; for a train seat, the coach and seat number together. These are the key fields. The code below uses them.
Example 3 · Fix: equals and hashCode on the roll number
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Objects;import java.util.Set;
class Student { private final int roll; private final String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
int getRoll() { return roll; }
@Override public boolean equals(Object o) { return o instanceof Student other && roll == other.roll; }
@Override public int hashCode() { return Objects.hash(roll); }
@Override public String toString() { return roll + "-" + name; }}
public class HostelRegistrationDemo { public static void main(String[] args) { Student[] forms = { new Student(104, "Arjun"), new Student(101, "Priya"), new Student(104, "Arjun K"), new Student(102, "Kavya"), new Student(101, "Priya S") };
Set<Student> hostel = new HashSet<>(); for (Student form : forms) { if (!hostel.add(form)) { System.out.println("Already registered: " + form); } }
List<Student> list = new ArrayList<>(hostel); list.sort((a, b) -> Integer.compare(a.getRoll(), b.getRoll())); System.out.println("Hostel list: " + list); }}Already registered: 104-Arjun K Already registered: 101-Priya S Hostel list: [101-Priya, 102-Kavya, 104-Arjun]
What this code does
- Both methods use the same key field,
roll. So104-Arjun Khas the same hash code as104-Arjun, lands in the same bucket, andequalssays they match. - The name is not a key field, so a different spelling does not create a second registration. The first form that was added is the one kept.
Example 4 · Records do the work for you
import java.util.HashSet;import java.util.Set;
record Seat(String coach, int number) {}
public class SeatBookingDemo { public static void main(String[] args) { Set<Seat> booked = new HashSet<>(); Seat[] requests = { new Seat("S1", 23), new Seat("S1", 24), new Seat("S2", 23), new Seat("S1", 23) };
for (Seat seat : requests) { if (booked.add(seat)) { System.out.println("Booked " + seat); } else { System.out.println("Sorry, " + seat + " is taken"); } } System.out.println("Seats booked: " + booked.size()); System.out.println("Is S2-23 taken? " + booked.contains(new Seat("S2", 23))); }}Booked Seat[coach=S1, number=23] Booked Seat[coach=S1, number=24] Booked Seat[coach=S2, number=23] Sorry, Seat[coach=S1, number=23] is taken Seats booked: 3 Is S2-23 taken? true
What this code does
- The record's
equalsandhashCodeuse bothcoachandnumber. So S1-23 and S2-23 are different seats, and the second S1-23 is a duplicate. - Record fields are final, so a seat can never change after it is in the set. That rules out the bug in the next example.
Then use exactly the same key fields in both methods. Objects.hash(coach, number) builds a good hash code from several fields, and Objects.equals(a, b) compares two fields safely even when one is null.
A record does all of this for you. record Seat(String coach, int number) gets equals and hashCode built from all its fields, and its fields cannot change. That makes records the safest choice for small values stored in sets.
hashCode that returns the same number for every object is legal but slow: every object lands in one bucket, and the set becomes a slow list.Do not change an element after adding it
A HashSet files each object in a bucket by its hash code when it is added. If a field used in hashCode changes later, the object stays in the old bucket while its new hash code points elsewhere. The code below shows it.
Example 5 · Changing an element hides it
import java.util.HashSet;import java.util.Objects;import java.util.Set;
class Member { private int id;
Member(int id) { this.id = id; }
void setId(int id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof Member other && id == other.id; }
@Override public int hashCode() { return Objects.hash(id); }
@Override public String toString() { return "Member " + id; }}
public class MutatedElementDemo { public static void main(String[] args) { Set<Member> gym = new HashSet<>(); Member m = new Member(101); gym.add(m); System.out.println("Before change: " + gym.contains(m));
m.setId(150); System.out.println("After change: " + gym.contains(m)); System.out.println("Removed? " + gym.remove(m));
gym.add(m); System.out.println("Size: " + gym.size()); System.out.println(gym); }}Before change: true After change: false Removed? false Size: 2 [Member 150, Member 150]
What this code does
- The object was filed under the hash code of id 101. After
setId(150), the set looks in the bucket for 150, finds nothing, and evenremovefails. - Adding it again stores the same object twice, which a set should never do. Keep key fields
final, or remove, change and re-add.
After that, contains and remove look in the wrong bucket and fail, even for the very same object. You can even add the same object a second time. The set is now quietly broken.
The fix: keep key fields final, or use a record. If a key really must change, remove the object, change it, and add it again.
Order of execution
Put the steps in order
What happens after a key field changes?
Next step
Check your understanding
12 quick questions