Do keys with different hashes also get mapped to the same index in HashMap?

前端 未结 3 1603
深忆病人
深忆病人 2021-01-13 02:43

Looking at the code specifically line 393, it looks like different hashes have been mapped to same index. I had an understanding that the hashcode is used to determine what

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 03:41

    Since a hashcode can be one in 2^32 values, it is rare that the hashmap has so many buckets (just the table would require 16GB of memory). So yes, you can have objects with different hashes in the same buckets of the maps (AFAIK it is a simple modulus operation of hachCode % numberOfBuckets).

    Note that the code does not use directly key.hashCode(), but hash(key.hashCode()).

提交回复
热议问题