Implementing hashCode() for Collections
The optimal implementation of hashCode() for a collection depends on its usage pattern. However, one widely-accepted approach proposed by Josh Bloch in his book "Effective Java" is as follows:
Algorithm:
- Assign a non-zero value to an integer variable result.
-
For each field f used in the equals() method:
- For boolean fields, calculate (f ? 0 : 1).
- For numeric fields (byte, char, short, int), calculate (int)f.
- For long fields, calculate (int)(f ^ (f >>> 32)).
- For float fields, calculate Float.floatToIntBits(f).
- For double fields, calculate Double.doubleToLongBits(f) and treat the result as a long value.
- For object fields, use the hashCode() method of the object or 0 if f is null.
- For array fields, recursively calculate the hash values of each element and combine them.
- Combine each hash value c with result: result = 37 * result c.
- Return result.
Advantages:
- Provides a reasonable distribution of hash values for most use cases.
- Methodic approach ensures consistent behavior across different data types.
- Sensitive to changes that affect object equality.
The above is the detailed content of How to Effectively Implement hashCode() for Collections?. For more information, please follow other related articles on the PHP Chinese website!