I am writing a java program which uses hashmap. I know how a hashmap works. If I add(key,object), then the java finds the hashcode of the key and uses that to find a bucket to store the object.
Now I have my own hashcode implementation for the object. And I want to give this as the key – something like add(object.hashcode(),object).
Is it possible to prevent java from again hashing object.hashcode()? Because I am already implementing hashcode() calling hashcode() on hashcode will be a waste of time.
I am writing a java program which uses hashmap. I know how a hashmap
Share
The way to do it is to implement
hashCode()to cache the hash value once it is calculated. Do note that this implies your object is immutable, or at least the fields contributing tohashCodeandequalsdon’t change after putting the object into the map.You don’t need to use the hashcode as the key. Moreover, that would almost certainly be the wrong way to do it because it is actually not how hashtables are supposed to work. Hash collisions are the name of the game, so the hashcode is only used to address a bucket, but (the name says it all) a bucket contains not one, but arbitrarily many objects. These must be checked by
equalsto find the exact one you were looking for.Given your initial idea to use hashcode as the key, it looks like you are not really after a map, but after
HashSet. You are just adding objects into a collection and will later want to check an object’s presence in it. That is a set.