Sobes.tech
Junior — Middle

Can you explain what the hashCode method in Java is used for and how it is implemented?

sobes.tech AI

Answer from AI

The hashCode() method in Java is used to obtain the hash code of an object — an integer that serves for quick comparison of objects, for example, in hash tables (HashMap, HashSet).

Implementation rules:

  • If two objects are equal according to the equals() method, then their hashCode() should return the same value.
  • If objects are not equal, it is desirable that their hash codes are different, but this is not mandatory.

Example implementation for a class with two fields:

@Override
public int hashCode() {
    int result = 17;
    result = 31 * result + (field1 != null ? field1.hashCode() : 0);
    result = 31 * result + (field2 != null ? field2.hashCode() : 0);
    return result;
}

Here, 31 is a prime number, often used to reduce collisions.

Can you explain what the hashCode method in Java is… - sobes.tech