首页 > 其他 > 详细

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

时间:2020-03-21 18:31:49      阅读:224      评论:0      收藏:0      [点我收藏+]

这个问题应该倒过来思考,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次幂

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

原文:https://www.cnblogs.com/gabriel-y/p/12540420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!