Ashwin
Ashwin

Reputation: 13527

Using my own hashcode for hashmap java

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.

Upvotes: 0

Views: 733

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200158

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.

Upvotes: 6

muruga
muruga

Reputation: 1073

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.

Upvotes: 1

Related Questions