Sobes.tech
Junior

What is the difference between the equals and hashCode methods in Java?

sobes.tech AI

Answer from AI

The equals method is used to compare objects for equality of their content, while hashCode returns an integer value that represents the object's hash code.

Main differences:

  • Purpose: equals for determining logical equality, hashCode for generating a hash code (usually for use in hash data structures).
  • Result: equals returns a boolean (true or false), hashCode returns an int.
  • Contract: If two objects are equal according to equals, their hashCode must be the same. The reverse is not true: objects with the same hashCode can have different contents (collision).
  • Usage: equals is used for pairwise comparison of objects. hashCode is used in hash-based collections (e.g., HashSet, HashMap) for quick object lookup.

Example:

// Example class
class MyObject {
    private int id;
    private String name;

    public MyObject(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Override equals
    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Identity check
        if (o == null || getClass() != o.getClass()) return false; // Type and null check
        MyObject myObject = (MyObject) o; // Type casting
        return id == myObject.id && Objects.equals(name, myObject.name); // Field comparison
    }

    // Override hashCode
    @Override
    public int hashCode() {
        return Objects.hash(id, name); // Generate hash code based on fields
    }
}

It is important to override both methods (equals and hashCode) together, if one of them is overridden, to avoid breaking the contract and to ensure correct operation of collections.

What is the difference between the equals and… - sobes.tech