The role of hash (key)

problem

Today ’s question: We know that the hashCode () function of the Object class is used to map objects to int values ​​in a hash table, and then calculate the hash value based on this int value to determine its position in the hash table. , In Hashtable you can see how he did this:

int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;

But in HashMap,

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
putVal(hash(key), key, value, false, evict)
tab[i = (n - 1) & hash]

It can be seen that he first called the hash (key) function and then processed it. Today's question is, what does this function do to preprocess the hashcode?
ps: Do not answer the null pointer, this is not what this question wants to ask.

answer

This function is very simple, that is, use the high and low bits of hashcode to do an XOR operation, so what is his role?

This problem starts with the performance of HashMap. We know that the performance of HashMap search and addition is completely related to the length of the linked list corresponding to the current hash value, and the length of the linked list is the number of hash values ​​of the data stored in the current HashMap, and the hash value of HashMap The remainder of the hash (key) divided by the tab length (must be an exponent of 2) is used, which is the low-order number of hash (key), so this method uses the high-order and status to do an XOR operation together, which can increase the low-order Unordered degree, reduce the possibility of equal hash value, so as to improve the performance of HashMap.

Published 19 original articles · praised 8 · visits 4040

Guess you like

Origin blog.csdn.net/u014068277/article/details/103951235