HashMap Performance when overriding hashcode method

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

    If you are referring to the asymptotic time complexity then:

    since HashMap uses hashCode to calculate which bucket to use in the hashtable if you return 1 from hashCode you effectively make your HashMap's performance be like an (unsorted) LinkedList's performance.

    Returning random values will simply blow your HashMap up since equal objects will no longer have equal hashCodes.

    Excerpt from Wikipedia:

    +----------------------+----------+------------+----------+--------------+
    |                      |  Insert  |   Delete   |  Search  | Space Usage  |
    +----------------------+----------+------------+----------+--------------+
    | Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
    | Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
    +----------------------+----------+------------+----------+--------------+
    

    So to sum it up you lose:

    • Time complexity when searching your HashMap (from O(1) to O(n))
    • lookup in your HashMap (it won't work anymore)

提交回复
热议问题