HashMap Performance when overriding hashcode method

后端 未结 5 989
悲&欢浪女
悲&欢浪女 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条回答
  •  猫巷女王i
    2021-02-06 11:25

    If you always returned 1 (or any other constant value for all objects to be inserted), then the HashMap would internally degrade to be a "linked list". This means that insertion, deletion and querying would no longer have a complexity of O(1), but of O(n), and impose a potentially severe performance penalty.

    If you returned random values, then the HashMap would simply become inconsistent. It could happen that the "same" key appeared twice (although according to the specification, each key may only appear once). It may also happen that you will not find the value for a certain key, although you previously inserted it (with a different hashCode).

    The exact behavior will then also depend on the implementation of the equals method, but these are the main effects that such an implementation would have.

提交回复
热议问题