首页 > 其他分享 >Integer和int为什么在-128-127之间比较会相等

Integer和int为什么在-128-127之间比较会相等

时间:2023-07-18 11:13:39浏览次数:37  
标签:int archivedCache static 127 128 Integer size

原因:

因为在Integer.class文件中,有一个静态内部类IntegerCache;
会在系统加载时,将(low = -128到h = 127)之间的数据提前包装成Integer对象放入数组cache中;

int a = 111l;
Integer c = 111l;
System.out.println(a==c); // 在次会发生自动的装箱,将a转换成Integer在对比

字节码文件可以看出来,使用的是valueOf()方法将int转为了Integer对象;如果数值在(low = -128到h = 127)之间,会去IntegerCache.cache[]数组中查找并返回;
因为是同一个对象,所以使用判断肯定是true;如果不在(low = -128到h = 127),会创建一个新的Integer对象,用判断肯定就不等了;可以使用equals()对比,会将Integer先转为int值,再对比就相等了
image.png

@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
    return value == ((Integer)obj).intValue();
}
return false;
}

同理

byte,short,int,long都是如此,区间默认都是(-128到127),Character是127
但是只有integer的最大范围是可以调整的;
配置java.lang.Integer.IntegerCache.high // 可以调整127的上限,不能大于int的最大值

源码:

IntegerCache源码:

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer[] cache;
    static Integer[] archivedCache;

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
        VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); // 可以调整127的上限,不能大于int的最大值
        if (integerCacheHighPropValue != null) {
            try {
                h = Math.max(parseInt(integerCacheHighPropValue), 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        // Load IntegerCache.archivedCache from archive, if possible
        CDS.initializeFromArchive(IntegerCache.class);
        int size = (high - low) + 1;

        // Use the archived cache if it exists and is large enough
        if (archivedCache == null || size > archivedCache.length) {
            Integer[] c = new Integer[size];
            int j = low;
            for(int i = 0; i < c.length; i++) {
                c[i] = new Integer(j++); // 包装成Integer对象放入数组
            }
            archivedCache = c;
        }
        cache = archivedCache;
        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

CharacterCache源码:

private static class CharacterCache {
    private CharacterCache(){}

    static final Character[] cache;
    static Character[] archivedCache;

    static {
        int size = 127 + 1;

        // Load and use the archived cache if it exists
        CDS.initializeFromArchive(CharacterCache.class);
        if (archivedCache == null || archivedCache.length != size) {
            Character[] c = new Character[size];
            for (int i = 0; i < size; i++) {
                c[i] = new Character((char) i);
            }
            archivedCache = c;
        }
        cache = archivedCache;
    }
}

LongCache源码:

private static class LongCache {
    private LongCache() {}

    static final Long[] cache;
    static Long[] archivedCache;

    static {
        int size = -(-128) + 127 + 1;

        // Load and use the archived cache if it exists
        CDS.initializeFromArchive(LongCache.class);
        if (archivedCache == null || archivedCache.length != size) {
            Long[] c = new Long[size];
            long value = -128;
            for(int i = 0; i < size; i++) {
                c[i] = new Long(value++);
            }
            archivedCache = c;
        }
        cache = archivedCache;
    }
}

ByteCache源码:

private static class ByteCache {
    private ByteCache() {}

    static final Byte[] cache;
    static Byte[] archivedCache;

    static {
        final int size = -(-128) + 127 + 1;

        // Load and use the archived cache if it exists
        CDS.initializeFromArchive(ByteCache.class);
        if (archivedCache == null || archivedCache.length != size) {
            Byte[] c = new Byte[size];
            byte value = (byte)-128;
            for(int i = 0; i < size; i++) {
                c[i] = new Byte(value++);
            }
            archivedCache = c;
        }
        cache = archivedCache;
    }
}

ShortCache源码

private static class ShortCache {
    private ShortCache() {}

    static final Short[] cache;
    static Short[] archivedCache;

    static {
        int size = -(-128) + 127 + 1;

        // Load and use the archived cache if it exists
        CDS.initializeFromArchive(ShortCache.class);
        if (archivedCache == null || archivedCache.length != size) {
            Short[] c = new Short[size];
            short value = -128;
            for(int i = 0; i < size; i++) {
                c[i] = new Short(value++);
            }
            archivedCache = c;
        }
        cache = archivedCache;
    }
}

标签:int,archivedCache,static,127,128,Integer,size
From: https://www.cnblogs.com/lzghyh/p/17562338.html

相关文章

  • Windows Intelnet 属性中的隐私弹出窗口阻止程序设置设置为高级别
    要通过批处理将WindowsIntelnet属性中的隐私弹出窗口阻止程序设置设置为高级别,你可以使用以下命令:REGADD"HKCU\Software\Microsoft\Windows\CurrentVersion\InternetSettings\Zones\3"/v1406/tREG_DWORD/d3/f这个命令会将注册表键值1406设置为3,表示阻止级别设置......
  • Proj. CMI Paper Reading: R-U-SURE? Uncertainty-Aware Code Suggestions By Maximiz
    AbstractTask:buildinguncertainty-awaresuggestionsbasedonadecision-theoreticmodelofgoal-conditionalutility,推理LLM用户的未观测到的意图方法:adecision-theoreticmodelofgoal-conditionedutility,使用生成式模型生成的randomsamples来做proxy,minimumBa......
  • 题解 CF1271D
    贪心+DP。对于一个点,后选显然比先选好,也就是说每个点都对应了唯一一个来源。于是我们可以把每个点所能回溯到的点的收益值从大到小排序,贪心地选前缀。定义\(f_{i,j}\)表示考虑了前\(i\)个点,剩下\(j\)个人,最大收益。转移方程和\(01\)背包的一样。\[f_{i,j}=f_{i-1,j-b......
  • [论文研读]空天地一体化(SAGIN)的网络安全_A_Survey_on_Space-Air-Ground-Sea_Integra
    ------------恢复内容开始------------空天地一体化(SAGIN)的网络安全目前关注的方面:集中在安全通信、入侵检测、侧通道攻击、GPS欺骗攻击、网络窃听、消息修改/注入等方面,有些侧重于分析现有的安全威胁[20]、[21],有些提出了他们的攻击方法[14]、[22],还有一些则更多地侧重于SAG......
  • 使用Power Automate上传附件到Dynamics 365集成的SharePoint
      在Dynamics365中使用SharePoint集成做实体的附件管理,这里不像用Annotation实体存放附件可以直接用代码直接创建Annotation记录,如果想要对外部提供接口把附件上传到SharePoint,我们可以使用PowerAutomate中的SharePoint组件来生成文件,通过HTTP流供给外部系统调用。  下......
  • IntelliJ IDEA 永久开发工具下载安装详细教程
    简介IDEA全称IntelliJIDEA,是java编程语言的集成开发环境。IntelliJ在业界被公认为最好的Java开发工具下载安装►官网地址:https://www.jetbrains.com/idea►快速下载(官方安装包等工具)IDEA有两个版本,一个是Ultimate(旗舰版)一个是Community(社区版),旗舰版可以免费试用......
  • 127. 单词接龙
    字典wordList中从单词beginWord和endWord的转换序列是一个按下述规格形成的序列beginWord->s1->s2->...->sk:每一对相邻的单词只差一个字母。对于1<=i<=k时,每个si都在wordList中。注意,beginWord不需要在wordList中。sk==endWord给你两个单词......
  • POST XXX 500 (Internal Server Error)
    详细信息“/”应用程序中的服务器错误。分析器错误说明: 在分析向此请求提供服务所需资源时出错。请检查下列特定分析错误详细信息并适当地修改源文件。分析器错误消息: 未能创建类型“WebApp.FileUploadHandler”。源错误:行1:<%@WebHandlerLanguage="C#"CodeBe......
  • GET XXX 500 (Internal Server Error),
     详细信息 GEThttp://lXXX]500(InternalServerError)  jquery.min.js:4   点击Network查看详细的报错信息如下当前标识(IISAPPPOOL\DefaultAppPool)没有对“C:\ASP.NETFiles”的写访问权限。 参考:https://www.cnblogs.com/axel10/p/8746891.html ......
  • 编写一个函数,令其交换两个int指针
    #include<iostream>#include<Windows.h>usingnamespacestd;voidChange1(int*&a,int*&b){int*tmp=a;a=b;b=tmp;}intmain(){inta=6,b=221;int*p=&a,*q=&b;cout<<"......