加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java整数内存分配

发布时间:2020-12-15 02:50:15 所属栏目:Java 来源:网络整理
导读:嘿,我想了解下面的代码片段. public static void main(String[] args) { Integer i1 = 1000; Integer i2 = 1000; if(i1 != i2) System.out.println("different objects"); if(i1.equals(i2)) System.out.println("meaningfully equal"); Integer i3 = 10; In
嘿,我想了解下面的代码片段.
public static void main(String[] args) {
    Integer i1 = 1000;
    Integer i2 = 1000;
    if(i1 != i2) System.out.println("different objects");
    if(i1.equals(i2)) System.out.println("meaningfully equal");
    Integer i3 = 10;
    Integer i4 = 10;
    if(i3 == i4) System.out.println("same object");
    if(i3.equals(i4)) System.out.println("meaningfully equal");
}

此方法运行所有println指令.那是i1!= i2是真的,但是i3 == i4.乍一看这让我觉得奇怪,它们应该是不同的参考.我可以弄清楚,如果我将相同的字节值(-128到127)传递给i3和i4,它们将始终等于引用,但任何其他值将使它们不同.

我无法解释这一点,您能指出一些文档或提供一些有用的见解吗?

谢谢

解决方法

将int值自动装箱到Integer对象将使用缓存来获取常用值(因为您已经识别它们).这在 JLS at §5.1.7 Boxing Conversion中指定:

If the value p being boxed is true,false,a byte,a char in the range u0000 to u007f,or an int or short number between -128 and 127,then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

请注意,仅当语言为您自动为您设置值或使用Integer.valueOf()时才会应用此选项.使用new Integer(int)将始终生成新的Integer对象.

次要提示:JVM实现也可以自由地缓存这些范围之外的值,因为没有指定相反的值.但是,我还没有看到这样的实现.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读