HashMap下标计算详解

HashMap 计算方法为:(n - 1) & hash 具体见putVal
解读:由于n-1高位全部为0 因此(n - 1) & hash只会得到一个小于等于n-1的值,即在桶长度取值范围内.
为何不用取余运算,写一段模拟程序,我们来对比下速度:

        Random random = new Random();
        int[] array =new int[8];
        int[] array2 =new int[8];
        long start = System.currentTimeMillis();
        int [] randNum = new int[1000000000];
        for (int i = 0; i < 1000000000; i++) {
            randNum[i] = random.nextInt(Integer.MAX_VALUE);
        }
        System.out.println("随机数生成s耗时"+(System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            int temp = randNum[i];
            int temp1 = temp & 7;
            array[temp1] ++;
        }
        System.out.println("&运算耗时"+(System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            int temp = randNum[i];;
            int temp2 = temp % 8;
            array2[temp2] ++;
        }
        System.out.println("%运算耗时"+(System.currentTimeMillis() - start));
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(array2));

运行结果:

随机数生成s耗时16047
&运算耗时842
%运算耗时1135
[125000039, 125000018, 125000011, 125000048, 124999883, 125000270, 124999981, 124999750]
[125000039, 125000018, 125000011, 125000048, 124999883, 125000270, 124999981, 124999750]

我们把数字改成5

随机数生成s耗时15465
&运算耗时1085
%运算耗时1738
[499999525, 0, 0, 0, 500000475]
[200012563, 199986986, 199985673, 199981177, 200033601]

结论:

&位运算速度快于%,缺点:某些奇数如5 时分布不均匀。
联系下另一个方法:tableSizeFor 会将我们传入容量返回为2的倍数。经过实际测试 16 ,32 &位运算比较均匀。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 HashMap HashMap类继承图 HashMap属性 HashMap构造函数HashMap(int i...
    HikariCP阅读 5,859评论 0 5
  • 目的 深入讲解HashMap源码,如题,将从put(K key, V value)方法调用开始 put方法 当传入...
    IT那些事儿阅读 1,193评论 0 0
  • 简介 在JDK1.8之前,HashMap采用数组+链表实现,即使用链表处理冲突,同一hash值的节点都存储在一个链...
    JourWon阅读 3,660评论 2 13
  • 本着针对面试,不负责任的态度,写下《面试总结》系列。本系列记录面试过程中各个知识点,而不是入门系列,如果有不懂的自...
    DB_BOY阅读 4,697评论 0 4
  • 可以搜索微信公众号【Jet 与编程】查看更多精彩文章 原文发布于自己的博客平台【http://www.jetche...
    goldenJetty阅读 2,256评论 0 1

友情链接更多精彩内容