为什么HashMap的容量要是2的幂

看一下HashMap的get()方法

	public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
	final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

根据key的hashcode获取下标进而得到链表头节点元素tab[(n - 1) & hash],计算下标是用的(n - 1) & hash

若n为2的幂,n-1的二进制第一位是0,后面全是1,当与hash做&运算时,比较均匀,减少hash碰撞。为什么比较均匀呢?

因为0&任何数都等于0,如果出现0,这样算出来的下标某些位永远是0,所以不均匀。

比如15&(0-15)的值就是0-15,没有任何冲突

实时内容请关注微信公众号,公众号与博客同时更新:程序员星星
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章