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:
-
Consistency with equals: If two objects are equal according to the
equals()method, then theirhashCode()should return the same value. -
Stability: The
hashCodevalue for an object should not change during the lifetime of the object, provided that the fields involved in the calculation do not change. -
Good distribution: The method should aim to distribute hash codes evenly to reduce the number of collisions in hash tables.
-
Use of significant fields: When computing
hashCode, use the fields that participate in theequalscomparison.
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.