Sobes.tech
Junior — Middle

How to properly modify an object so that it can be used in a HashMap collection?

sobes.tech AI

Answer from AI

For an object to be used correctly in a HashMap collection, it is necessary to properly override the equals() and hashCode() methods.

  • hashCode() should return the hash code of the object, which is used to determine the bucket in HashMap.
  • equals() determines whether two objects are considered equal.

Rules:

  • If two objects are equal according to equals(), then their hashCode() must be the same.
  • If the hashCode() of objects is different, then equals() can be false.

Example:

public class Person {
    private String id;
    private String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id.equals(person.id);
    }

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

In this example, objects are considered equal if they have the same id. This guarantees correct operation in HashMap.

If these methods are not overridden, HashMap will use the implementation from Object, which can lead to incorrect behavior (for example, different objects with the same data will be considered different keys).

How to properly modify an object so that it can be… - sobes.tech