HASHMAP 原理学习

143 阅读1分钟

模运算

www.cs.cmu.edu/~adamchik/1…

取模可以转换成二进制的位与运算当d为2的指数幂
n % d = n & (d-1)

You can do modulus very efficiently for a power of 2. n % d = n & (d-1) when d is a power of 2, and modulus is used to determine which index an item maps to in the internal array – which means it occurs very often in a Java HashMap.

There’s one more thing about choosing the hash & (n – 1) versus modulo and that is negative hashes. hashcode is of type int, which of course can be negative. modulo on a negative number (in Java) is negative also, while & is not.

HashMap’s null key and null value

In the Javadoc of HashMap, there is one sentence below:

HashMap permits null values and the null key
When we look into the source code, we find the null key’s hashcode is set to 0, and 0%n(the current capicity of hashtable) always equals 0, so the null key’s node always allocated at the 0 index of the hashtable.

the difference between HashMap and HashTable

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

  1. after my test demo, hashtable not only doesn’t accept null key but also null value, below is why hashtable can not put null key, null value
  1. HashTable use synchronized to implement synchronize mechanism.

HashMap 的无序性

HashMap 不能保证Map中元素的插入顺序和遍历顺序一致,也不能保证时间上的顺序一致