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.
2 Answers
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 to hashCode and equals don'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 equals to 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.
6 Comments
equals. These two methods must always be implemented together, and consistently.equals as a second check, before finding the corect reference. hashcode should return the same value for two objects that are equal. A better implementation of hashcode (by better I mean an implementation that returns a trully different value for each object) improves performance by reducing the amount of objects on the second level (same hashcode) check that is made with equals.Unless you have your own implementation, you can't do that. The reason is that the hashing is used to pick your objects when you use the get method.
hashCodemethod of the object in question?map.put(object, object).