Sobes.tech
Junior — Middle

What happens when the hashCode method is called on an object if this method has not been explicitly overridden in the class?

sobes.tech AI

Answer from AI

If the hashCode() method is not overridden in a class, the hashCode() method from the Object class will be called.

By default, Object.hashCode() returns an integer value that is usually based on the internal address of the object in memory or another unique identifier provided by the JVM.

This means that:

  • Different instances of the object, even if they are logically equal, will have different hash codes.
  • If you override the equals() method, it is recommended to also override hashCode() to ensure the correct operation of collections such as HashMap or HashSet.

Example:

class Person {
    String name;
    // equals is overridden, but hashCode is not
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person p = (Person) o;
        return name.equals(p.name);
    }
}

Person p1 = new Person();
p1.name = "Alice";
Person p2 = new Person();
p2.name = "Alice";

System.out.println(p1.equals(p2)); // true
System.out.println(p1.hashCode() == p2.hashCode()); // false if hashCode is not overridden

Thus, without overriding hashCode(), objects with the same data may have different hash codes, which can lead to errors when used in hash-based structures.