გადაწყდაHashSet keeps "duplicates" even though I overrode equals

KW Kate W. წევრი რეგისტრაცია: 4 სექ. 2026
პოსტები: 20
#1

Hello everyone, I'm working through a Java course and I'm properly stuck on an exercise. I override equals so two listings with the same code are equal, yet a HashSet happily keeps both:

import java.util.HashSet;
import java.util.Set;

class Listing {
    String code;
    int price;

    Listing(String code, int price) {
        this.code = code;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Listing other)) return false;
        return code.equals(other.code);
    }
}

public class Main {
    public static void main(String[] args) {
        Set<Listing> set = new HashSet<>();
        set.add(new Listing("A-1", 100));
        set.add(new Listing("A-1", 100));
        System.out.println(set.size()); // prints 2
    }
}

What am I missing?

ER Evgeny Rudenko წევრი რეგისტრაცია: 14 აგვ. 2026
პოსტები: 86
#2

You overrode equals but not hashCode. A HashSet first picks a bucket by hashCode(), and only compares with equals() inside that bucket. Two objects with the default identity hash land in different buckets and never get compared.

The contract: if a.equals(b), then a.hashCode() == b.hashCode(). Use the same fields in both:

@Override
public int hashCode() {
    return code.hashCode();
}

And don't change code while the object is inside a set or used as a map key: the set won't find it any more.

YS Yury Slinkin თანამშრომელი · ადმინი რეგისტრაცია: 6 ივნ. 2026
პოსტები: 94
#3

If the class is just data, a record writes equals, hashCode and toString for you, from all components:

record Listing(String code, int price) {}

One catch: then equality covers price too, so new Listing("A-1", 100) and new Listing("A-1", 120) are different. If identity is only the code, either keep your class with the two methods, or store them in a Map<String, Listing> keyed by code.

KW Kate W. წევრი რეგისტრაცია: 4 სექ. 2026
პოსტები: 20
#4

>>3
Lovely, that makes sense. The exercise later asks to change the price, though. Can a record do that?

ER Evgeny Rudenko წევრი რეგისტრაცია: 14 აგვ. 2026
პოსტები: 86
#5

>>4
No, record fields are final. You make a new one:

Listing updated = new Listing(old.code(), 120);

That is the intended style for records: values, not objects with changing state. If the exercise really wants a mutable listing, a regular class is the right tool there.

AK Anna Kor წევრი რეგისტრაცია: 4 ივლ. 2026
პოსტები: 93
#6

A short list for the course notes:
✅ override equals and hashCode together, using the same fields
✅ let the IDE generate them, or use Objects.equals / Objects.hash
✅ don't mutate fields used in hashCode while the object is in a set or map
✅ records for plain values; they are immutable
✅ JPA entities are not records: Hibernate needs a no-arg constructor and mutable fields

სწრაფი პასუხი

წერა შეუძლიათ მხოლოდ შესულ წევრებს. შესვლა