Mercenary
Mercenary

Reputation: 2176

Does computing hashCode in HashMap and HashTable work differently?

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(..)?

Upvotes: 1

Views: 861

Answers (2)

Debojit Saikia
Debojit Saikia

Reputation: 10632

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.

Upvotes: 2

Tom Anderson
Tom Anderson

Reputation: 47253

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.

Upvotes: 1

Related Questions