博客
关于我
Java Integer类源码分析
阅读量:530 次
发布时间:2019-03-08

本文共 1119 字,大约阅读时间需要 3 分钟。

最近我在研究Integer类,记录一下我的发现。Integer是Java中int类型的包装类,它的值由内部属性value存储,最大值是0x7fffffff,最小值是0x80000000。Integer还维护了一个内部缓存IntegerCache,用于缓存-128到127之间的整数值。当调用Integer.valueOf(int i)时,优先从缓存中获取值。

举个例子,创建几个Integer对象:

Integer a = new Integer(1);
Integer b = new Integer(1);
Integer c = 1; // 使用自动拆箱
Integer d = 1;
Integer e = 128;
Integer f = 128;

运行这段代码,结果分别是:

a == b → false
c == d → true
e == f → false

这说明在-128到127范围内的整数值会被缓存,而128及以上则不会。

接下来,我看了Integer的常用方法。hashCode()方法返回的是Integer本身的值,这很有用。另外,Integer还有一个静态方法hashCode(int value),同样返回value。

然后,我深入研究了parseInt(String s, int radix)方法。这个方法可以将字符串转换为不同进制的整数,radix的范围是2到36。代码中首先检查s是否为null,接着检查radix的范围。然后初始化result为0,处理负数情况,逐步计算每一位数字,确保结果不会超过Integer.MAX_VALUE。

parseInt的实现有几个关键点:

  • 处理正负号,确定数值范围。
  • 从最高位开始逐位转换,使用乘法和减法来计算最终结果。
  • 处理进位和溢出情况,确保转换过程中的准确性。
  • 再来看Integer.toString(int i)方法,这是parseInt的逆向操作。对于i=2147483647,返回"2147483647",而i=Integer.MIN_VALUE则直接返回"-2147483648"。stringSize(int x)方法用于计算整数的字符长度,使用了一个预定义的sizeTable数组来优化长度计算。

    最后,getChars(int i, int index, char[] buf)方法用于将整数转换为字符数组。对于大数,使用位移和减法来分解数字,提高转换效率。对于小数,则使用除法和取模的方式。

    总的来说,Integer类在处理int类型的包装、缓存优化、字符串转换以及不同进制转换方面都有详细的实现。这些功能对于日常编程和数值处理都非常有用。

    转载地址:http://vsgnz.baihongyu.com/

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No static resource favicon.ico.
    查看>>