<返回更多

HashMap初始容量总结,彻底吃透位运算,简历立马多项熟练

2021-04-06  今日头条  java分享者
加入收藏

 

场景描述

我们在日常学习和研发中,经常会接触一些底层的源码,有些同学在遇到位运算(提高系统的运行效率)实现的方法时,读起来就有些吃力了,例如HashMap类中的tableSizeFor(int cap)方法,源代码如下。

/**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

当我们使用HashMap集合没有指定初始容量时默认是16,如果给定了一个初始容量,tableSizeFor(int cap)方法会返回一个等于2的n次方的数来作为集合的初始容量。如果用户给定的初始容量就等于2的n次方,那么返回的这个数就等于用户给定值,否则将会返回一个大于且最接近用户给定值的2的n次方的数来作为HashMap集合的初始容量。

案例演示

为了演示效果我这里使用反射的方式直接调用HashMap类里的tableSizeFor(int cap)方法测试容量的返回值。有对反射不是很理解的同学可以将源码复制出来测试也可以在这个方法上添加断点debug调试。

代码示例

假设用户给定初始容量 cap=7

import JAVA.lang.reflect.Method;
public class Demo {
    public static void main(String[] args) throws Exception {
        Class aClass = Class.forName("java.util.HashMap");
        Object instance = aClass.newInstance();
        Method tableSizeFor = aClass.getDeclaredMethod("tableSizeFor", int.class);
        //设置目标类中的tableSizeFor方法可访问
        tableSizeFor.setAccessible(true);
        //假设用户给定的初始值时cap=7
        Object invoke = tableSizeFor.invoke(instance, 7);
        //打印返回值
        System.out.println("tableSizeFor方法返回值:"+invoke);
    }
}

运行结果

F:softwareJavajdk1.8.0_121binjava.exe "-javaagent:D:IntelliJ IDEA 2019.1.4libidea_rt.jar=51583:D:IntelliJ IDEA 2019.1.4bin" -Dfile.encoding=UTF-8 -classpath F:softwareJavajdk1.8.0_121jrelibcharsets.jar;F:softwareJavajdk1.8.0_121jrelibdeploy.jar;F:softwareJavajdk1.8.0_121jrelibextaccess-bridge-64.jar;F:softwareJavajdk1.8.0_121jrelibextcldrdata.jar;F:softwareJavajdk1.8.0_121jrelibextDNSns.jar;F:softwareJavajdk1.8.0_121jrelibextjaccess.jar;F:softwareJavajdk1.8.0_121jrelibextjfxrt.jar;F:softwareJavajdk1.8.0_121jrelibextlocaledata.jar;F:softwareJavajdk1.8.0_121jrelibextnashorn.jar;F:softwareJavajdk1.8.0_121jrelibextsunec.jar;F:softwareJavajdk1.8.0_121jrelibextsunjce_provider.jar;F:softwareJavajdk1.8.0_121jrelibextsunmscapi.jar;F:softwareJavajdk1.8.0_121jrelibextsunpkcs11.jar;F:softwareJavajdk1.8.0_121jrelibextzipfs.jar;F:softwareJavajdk1.8.0_121jrelibjavaws.jar;F:softwareJavajdk1.8.0_121jrelibjce.jar;F:softwareJavajdk1.8.0_121jrelibjfr.jar;F:softwareJavajdk1.8.0_121jrelibjfxswt.jar;F:softwareJavajdk1.8.0_121jrelibjsse.jar;F:softwareJavajdk1.8.0_121jrelibmanagement-agent.jar;F:softwareJavajdk1.8.0_121jrelibplugin.jar;F:softwareJavajdk1.8.0_121jrelibresources.jar;F:softwareJavajdk1.8.0_121jrelibrt.jar;D:ideastudyspacespring_studyspring-studyspring-study-proxytargetclasses;E:softwareMavenRepositoryorgspringframeworkspring-webmvc3.2.0.RELEASEspring-webmvc-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-context3.2.0.RELEASEspring-context-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-aop3.2.0.RELEASEspring-aop-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-core3.2.0.RELEASEspring-core-3.2.0.RELEASE.jar;E:softwareMavenRepositorycommons-loggingcommons-logging1.1.1commons-logging-1.1.1.jar;E:softwareMavenRepositoryorgspringframeworkspring-web3.2.0.RELEASEspring-web-3.2.0.RELEASE.jar;E:softwareMavenRepositoryaopallianceaopalliance1.0aopalliance-1.0.jar;E:softwareMavenRepositoryorgspringframeworkspring-expression3.2.0.RELEASEspring-expression-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-beans3.2.0.RELEASEspring-beans-3.2.0.RELEASE.jar;E:softwareMavenRepositorycomalibabafastjson1.2.47fastjson-1.2.47.jar com.shiguang.service.Demo
tableSizeFor方法返回值:8
Process finished with exit code 0

此时我们设置初始容量cap=9

import java.lang.reflect.Method;
public class Demo {
    public static void main(String[] args) throws Exception {
        Class aClass = Class.forName("java.util.HashMap");
        Object instance = aClass.newInstance();
        Method tableSizeFor = aClass.getDeclaredMethod("tableSizeFor", int.class);
        //设置目标类中的tableSizeFor方法可访问
        tableSizeFor.setAccessible(true);
        //将初始值时变更为cap=9
        Object invoke = tableSizeFor.invoke(instance, 9);
        //打印返回值
        System.out.println("tableSizeFor方法返回值:"+invoke);
    }
}

运行结果

F:softwareJavajdk1.8.0_121binjava.exe "-javaagent:D:IntelliJ IDEA 2019.1.4libidea_rt.jar=51640:D:IntelliJ IDEA 2019.1.4bin" -Dfile.encoding=UTF-8 -classpath F:softwareJavajdk1.8.0_121jrelibcharsets.jar;F:softwareJavajdk1.8.0_121jrelibdeploy.jar;F:softwareJavajdk1.8.0_121jrelibextaccess-bridge-64.jar;F:softwareJavajdk1.8.0_121jrelibextcldrdata.jar;F:softwareJavajdk1.8.0_121jrelibextdnsns.jar;F:softwareJavajdk1.8.0_121jrelibextjaccess.jar;F:softwareJavajdk1.8.0_121jrelibextjfxrt.jar;F:softwareJavajdk1.8.0_121jrelibextlocaledata.jar;F:softwareJavajdk1.8.0_121jrelibextnashorn.jar;F:softwareJavajdk1.8.0_121jrelibextsunec.jar;F:softwareJavajdk1.8.0_121jrelibextsunjce_provider.jar;F:softwareJavajdk1.8.0_121jrelibextsunmscapi.jar;F:softwareJavajdk1.8.0_121jrelibextsunpkcs11.jar;F:softwareJavajdk1.8.0_121jrelibextzipfs.jar;F:softwareJavajdk1.8.0_121jrelibjavaws.jar;F:softwareJavajdk1.8.0_121jrelibjce.jar;F:softwareJavajdk1.8.0_121jrelibjfr.jar;F:softwareJavajdk1.8.0_121jrelibjfxswt.jar;F:softwareJavajdk1.8.0_121jrelibjsse.jar;F:softwareJavajdk1.8.0_121jrelibmanagement-agent.jar;F:softwareJavajdk1.8.0_121jrelibplugin.jar;F:softwareJavajdk1.8.0_121jrelibresources.jar;F:softwareJavajdk1.8.0_121jrelibrt.jar;D:ideastudyspacespring_studyspring-studyspring-study-proxytargetclasses;E:softwareMavenRepositoryorgspringframeworkspring-webmvc3.2.0.RELEASEspring-webmvc-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-context3.2.0.RELEASEspring-context-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-aop3.2.0.RELEASEspring-aop-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-core3.2.0.RELEASEspring-core-3.2.0.RELEASE.jar;E:softwareMavenRepositorycommons-loggingcommons-logging1.1.1commons-logging-1.1.1.jar;E:softwareMavenRepositoryorgspringframeworkspring-web3.2.0.RELEASEspring-web-3.2.0.RELEASE.jar;E:softwareMavenRepositoryaopallianceaopalliance1.0aopalliance-1.0.jar;E:softwareMavenRepositoryorgspringframeworkspring-expression3.2.0.RELEASEspring-expression-3.2.0.RELEASE.jar;E:softwareMavenRepositoryorgspringframeworkspring-beans3.2.0.RELEASEspring-beans-3.2.0.RELEASE.jar;E:softwareMavenRepositorycomalibabafastjson1.2.47fastjson-1.2.47.jar com.shiguang.service.Demo
tableSizeFor方法返回值:16
Process finished with exit code 0

这个时候返回的是16,2的4次方,也是大于且最接近9的2的n次方的数。那么tableSizeFor(int cap)方法是如何实现这个功能的呢?

代码分析

首先我们先理解三个位运算符
“|” 或运算
举例:
0001
0010
------------------或运算(对应二进制位同是0时等于0,只要有1等于1)
0011
“|=” 或等于
举例:a |= b 就相当于 a = a | b
">>>" 无符号右移
举例:1001 >>> 2
1001
---------- 1001无符号右移2位
0010 01

了解以上位运算符,我们便可以轻松明白这个方法的原理了

用户指定HashMap初始数组容量 cap=9,进入tableSizeFor(int cap)方法
     1 [执行代码]:int n = cap - 1; n=8[最后我们再解释为什么这里要cap-1]
     2 [执行代码]: n |= n >>> 1;
       首先计算n >>> 1
       ------------------------------------------------------
         二进制         十进制           描述
       ------------------------------------------------------
       0000 1000         8            初始值
       ----------------------n >>> 1
       0000 0100~~0~~    4             结果
       接着计算 n|n >>> 1
       0000 1000         8
       0000 0100         4
       -------------------------------或运算
       0000 1100         12            结果
     3 [执行代码]: n |= n >>> 2;[注意]此时的n=0000 1100
       首先计算n >>> 2
       0000 1100         12
       -------------------------n >>> 2
       0000 0011~~00~~    3            结果
       接着计算 n|n >>> 2
       0000 1100         12
       0000 0011          3
       --------------------------------或运算
       0000 1111         15             结果
     4 [执行代码]: n |= n >>> 4;[注意]此时的n=0000 1111
       首先计算 n >>> 4
       0000 1111         15			   
       -------------------------n >>> 4
       0000 0000~~1111~~  0		        结果
       
       接着计算 n|n >>> 4
       0000 1111		 15
       0000 0000		  0
       --------------------------------或运算
       0000 1111         15
     5 [执行代码]: n |= n >>> 8;
       0000 1111         15             结果
     6 [执行代码]: n |= n >>> 16;
       0000 1111         15             结果
     ----------------------------------------------------
     我们不难发现规律
       start 0000 1000
       end   0000 1111
     初始值经过两轮[无符号右移]加[或运算]后已将最高二进制位上的1后面的所有二进制位都变成了1
     我们知道int类型占4个字节,也就是32位, 这样任意一个int类型的数进来经过这5轮[无符号右移]加[或运算],最高二进制位上的1后面的所有二进制位都会变成1
     接着我们执行这个方法的最后一行代码
     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
     显然此时我们的n=15,在[0,MAXIMUM_CAPACITY]这个区间内,所以
     return n + 1;
     系统设置HashMap集合的初始容量 cap=16;

那int n = cap - 1这行代码又有什么用呢?
显然这行代码是为了防止用户给定的初始值就等于2的n次方,如果用户给定值是8,而tableSizeFor(int cap)方法里没有cap - 1这行代码,那么方法的返回值就变成了16,这样就造成了不必要的内存浪费 。

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>