Java: A “prime” number or a “power of two” as HashMap size?

后端 未结 5 1237
醉梦人生
醉梦人生 2020-12-01 07:55

Many books and tutorials say that the size of a hash table must be a prime to evenly distribute the keys in all the buckets. But Java\'s HashMap always uses a s

5条回答
  •  醉话见心
    2020-12-01 08:43

    The standard HashMap implementation has a hash method which rehashes your object's hashcode to avoid that pitfall. The comment before the hash() method reads:

    /**
     * Retrieve object hash code and applies a supplemental hash function to the
     * result hash, which defends against poor quality hash functions.  This is
     * critical because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    

提交回复
热议问题