Home > Java > javaTutorial > How to Effectively Implement hashCode() for Collections?

How to Effectively Implement hashCode() for Collections?

Mary-Kate Olsen
Release: 2024-12-18 07:13:15
Original
207 people have browsed it

How to Effectively Implement hashCode() for Collections?

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:

  1. Assign a non-zero value to an integer variable result.
  2. 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.
  3. Combine each hash value c with result: result = 37 * result c.
  4. 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template