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
'; would there be any performance hit ?
if I change hashCode()
method to return random value using Math.random()
function
what would happen to performance ?
overriding doesn't add much overhead, if at all. The efficiency of your hashCode() implementation is up to what it has to do and how you write it. You could cache the value if it's important to you.
If we want to use instances of the Team class as HashMap keys, we have to override the hashCode() method so that it adheres to the contract; equal objects return the same hashCode.
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
Adding Math.random() doesn't affect much performance hit but it is a bad idea to construct hashcode values through random() function. Instead you can use some of the good hashing function to minimize the collision and which are much faster also. For reference you can check out some of the links http://www.partow.net/programming/hashfunctions/
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 hashCode
s.
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:
HashMap
(from O(1)
to O(n)
)HashMap
(it won't work anymore)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With