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
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.