简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM