1

I read couple of forums and I still fail to understand how is hashCode() computed and when?! I read in HashMap that hashCode() is called this way : hash(key.hashCode()); and in HashTable, it is computed with both the key and pair : h += e.key.hashCode() ^ e.value.hashCode();. Are they computed differently in HashMap and HashTable?

When do hashCode() gets called? I assume it happens when you try do a put(..), get(..) or delete(..)?

2
  • You could just look at the source-code... Commented Oct 29, 2013 at 12:24
  • The value can't be used to compute the hash, obviously. Otherwise, how could the get() method work to recompute the hash wihout any value? Commented Oct 29, 2013 at 12:27

2 Answers 2

2

The hashCode() of the key gets called when you put an item into the map:

public V put(K key, V value) {
...
int hash = hash(key.hashCode());
...
}

so that the new entry with the specified key, value and hash code can be added to the specified bucket.

It is also called when you are trying to retrieve a value from the map against the given key to find the bucket that has the required Entry. Again if you call containsKey to check whether a given key exists in the map, it uses hashCode to find the bucket that contains the Entry.

Sign up to request clarification or add additional context in comments.

Comments

1

You may be confusing two completely different uses of hashCode here, both of which exist in both HashMap and Hashtable.

The first, inside methods like put and get, is to compute the hash of a key to find an entry in the table of entries. That is what hash(key.hashCode()) is doing.

The second is inside the hashCode method of the HashMap or Hashtable itself, which is computing a single hash for the whole object. That uses the hashes of every key and value in the table - that's what h += e.key.hashCode() ^ e.value.hashCode() is doing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.