Sobes.tech
Junior

What is hashCode?

sobes.tech AI

Answer from AI

hashCode() is a method defined in the Object class that returns an integer value (hash code) for the object.

Main properties and purpose of hashCode():

  • Used in hash data structures: Its main purpose is efficient storage and retrieval of objects in collections that use hashing, such as HashSet, HashMap, and Hashtable. The hash code is used to determine the "bucket" in which an object may reside.
  • Relation to equals(): According to the Object contract, if two objects are considered equal by the equals() method, their hash codes returned by hashCode() should be the same. Conversely, two objects can have the same hash code but not be equal (this is called a collision).
  • Need for overriding: When overriding the equals() method, it is always necessary to override the hashCode() method as well, to maintain the Object contract and ensure correct behavior of hash collections.

Example of overriding hashCode():

public class MyClass {
    private int id;
    private String name;

    // ... constructor, getters, setters ...

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyClass myClass = (MyClass) o;
        return id == myClass.id &&
               Objects.equals(name, myClass.name);
    }

    @Override
    public int hashCode() {
        // Using Objects.hash() for convenient hash code calculation
        return Objects.hash(id, name);
    }
}

If hashCode() is not overridden when equals() is overridden, hash collections will not work correctly. For example, two objects considered equal by equals() might end up in different buckets, and methods like contains() or get() may not find them.

What is hashCode? — Java - sobes.tech