1

If I have a hashmap let's say map1 with hashsets as keys and another hashmap let's say map2 with integers as keys.

My query is what will be the performance for a lookup for a key in both the hashmaps ..??

Lookups are like this (Assuming keys don't exist in hashmaps)

map1.containsKey(6);
map2.containsKey(anyHashSet);

Which lookup will take more time or the lookup time will be same for both the cases and why ??

john smith
  • 11
  • 2
  • The lookup for the HashSet keyed HashMap will be a little longer but not that much. The reason is that java implementation of the Map using HashMap using an hash of the key. The hash acts just like the `.hashcode()` function of any object, actually I think it uses this method under the hood for each of its element. By contract, the hashcode function must return identic hashcode for two objects whose `.equals()` method return true. That means that two hashcodes can be identic but the two underlying objects might be different, but if two objects are equal, then their hashcodes MUST be identic. – Louis-wht Aug 23 '18 at 16:26
  • This is to be taken into account because `HashMap#get()` uses hascode first to compare two elements and if they are equal, then a second check is performed with .equals method which will be longer for the complex keyed HashMap – Louis-wht Aug 23 '18 at 16:27
  • Here in your example, `.equals` method which is the function which will make the complex keyed hashmap less effective will probably be called only once in a single lookup, that's why this won't make that much difference. BUT, the complex keyed implementation will have much more complex `.put` process because it will need to compute the hash of the new key which takes more time than with a simple keyed HashMap – Louis-wht Aug 23 '18 at 16:31
  • Thanks @Louis-Wht – john smith Aug 23 '18 at 16:43
  • 1
    Please see https://stackoverflow.com/questions/7842049/are-mutable-hashmap-keys-a-dangerous-practice as well. It is not really a good idea to use *mutable* keys for maps. Guess what: a hashset mutates each time you add/remove entries. – GhostCat Aug 23 '18 at 16:44
  • 1
    Thanks for the clarification, is it fine if I don't mutate the keys, I will be just adding some new hashsets as keys to the hashmap. @GhostCat – john smith Aug 23 '18 at 16:52
  • Just remember that decision down the road ;-) – GhostCat Aug 23 '18 at 17:10
  • Thanks, finally decided not to use HashSets as keys to the map. @GhostCat – john smith Aug 25 '18 at 11:24

0 Answers0