Sobes.tech
Junior — Middle

What happens if you add objects to HashSet that do not implement the equals() method?

sobes.tech AI

Answer from AI

If in Java objects added to a HashSet do not override the equals() method, the implementation from the Object class will be used, which compares objects by reference (i.e., two objects are considered equal only if they are the same reference in memory).

As a result, HashSet will consider different instances of objects as different elements, even if their internal data are identical. This can lead to duplicates from the application's logic perspective.

Additionally, for HashSet to work correctly, it is also important to override the hashCode() method, as HashSet uses hashing for quick element lookup. If hashCode() is not overridden, the implementation from Object will be used, which typically returns a unique value for each object.

Example:

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
    // equals() and hashCode() are not overridden
}

HashSet<Person> set = new HashSet<>();
set.add(new Person("Alice"));
set.add(new Person("Alice"));

System.out.println(set.size()); // Will output 2, although logically the objects are the same

To ensure HashSet works correctly with objects, you need to override equals() and hashCode() so that they consider the object's significant fields.