Sobes.tech
Junior — Middle

What are the main principles and recommendations when implementing the hashCode method for your classes?

sobes.tech AI

Answer from AI

Main principles and recommendations for implementing the hashCode method in Java:

  1. Consistency with equals: If two objects are equal according to the equals() method, then their hashCode() should return the same value.

  2. Stability: The hashCode value for an object should not change during the lifetime of the object, provided that the fields involved in the calculation do not change.

  3. Good distribution: The method should aim to distribute hash codes evenly to reduce the number of collisions in hash tables.

  4. Use of significant fields: When computing hashCode, use the fields that participate in the equals comparison.

Example implementation:

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

Here, the number 31 is chosen as a prime number to reduce collisions, and the initial value 17 is an arbitrary non-zero number.

What are the main principles and recommendations when… - sobes.tech