【HashMap】为什么HashMap的长度是2的N次幂?

这个问题应该倒过来思考,HashMap的长度是2的N次幂,有什么优势?

  在HashMap的putVal()方法中,为了确定插入元素在table[]数组中的下标位置,使用的与(&)运算来计算

  如下代码

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //这里使用与运算来计算当前插入的元素的下标位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {


  (n - 1) & hash 这个操作如果在n为2的N次幂的情况下是等同于 hash % n 取余数的值

  至于为什么要使用与(&)运算呢:

    因为与运算的效率要高于hash % n取余的运算

  这也就解释了为什么HashMap的数组长度是2的N次幂

猜你喜欢

转载自www.cnblogs.com/gabriel-y/p/12540420.html