HashMap Performance when overriding hashcode method

后端 未结 5 985
悲&欢浪女
悲&欢浪女 2021-02-06 10:34

In a HashMap, if I put custom objects as a key.

What would happen if I override hashCode() method and implement it to pass value as \'1

5条回答
  •  醉酒成梦
    2021-02-06 11:25

    Returning a fixed value in hashcode() will definitely make your hashtable run slower. All values will be assigned to the same bin, therefore lookup operations will take linear time (instead of the average constant time with a decent hash function).

    Returning a random value will break the hashmap contract completely. Values will be assigned to random bins and looked up in random bins, so nothing guarantees you'll find values stored previously.

提交回复
热议问题