HashMap Performance when overriding hashcode method

后端 未结 5 1097
悲&欢浪女
悲&欢浪女 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:10

    Always returning 1 in hashCode() will degrade the performance of HashMap. Every object defaults to the same bucket, and the hash tables become linked lists. According to Effective Java, item 9, you get quadratic time instead of linear.

    Returning a random value will violate the provision that equal objects have equal hashCodes, you won't be able to retrieve the stored objects.

提交回复
热议问题