Java Integer自动自动装箱 [英] Java Integer auto auto-boxing

查看:138
本文介绍了Java Integer自动自动装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java(JDK 1.7)中偶然发现了这一点:

I have stumbled upon this in Java (JDK 1.7):

    Integer a = 100;
    Integer b = 100;
    Integer c = 1000;
    Integer d = 1000;

    System.out.println(a == b); //true
    System.out.println(c == d); //false
    System.out.println(new Integer(100) == new Integer(100)); //false
    System.out.println(new Integer(1000) == new Integer(1000)); //false

输出为: 真的 错误的 错误的 错误

The output is: true false false false

为什么a == b评估为true?这是什么原因呢?这类似于String内部化吗?

Why does a==b evaluate to true? What is the reason for this? Is this similar to String internalization?

推荐答案

这类似于String内部化吗?

Is this similar to String internalization?

是-本质上,所有可容纳在一个字节中(-128至+127)的整数都将被插入,因此共享相同的基础对象.较大的不是,因此可能不会共享相同的基础对象(JLS 5.1.7对此进行了介绍)-尽管请注意,规范中没有任何东西可以阻止较大的整数共享相同的对象基础对象(如果有人选择以这种方式实现VM).

Yes - essentially all integers that can fit in a byte (-128 to +127) are interned and thus share the same underlying object. Larger ones aren't, and thus probably don't share the same underlying object (this is covered in JLS 5.1.7) - though note that there's nothing in the spec that prevents larger integers sharing the same underlying object if someone were to choose to implement a VM that way.

我会认为其基本原理是,使用此范围内的较小"整数要比使用较大整数更为频繁,因此使用相同的基础对象值得减少潜在的内存占用.

I would imagine the rationale is that "smaller" integers in this range are used much more often than larger ones, so using the same underlying objects is worth it to reduce the potential memory footprint.

在您的new Integer(100) == new Integer(100)示例中,情况并非如此,因为您正在显式创建新的整数对象,类似于new String("hi") == new String("hi")评估为false的方式.

In your new Integer(100) == new Integer(100) example, this isn't the case since you're explicitly creating new integer objects, similar to how new String("hi") == new String("hi") evaluates to false.

只需重申一下-在所有现实情况下比较这样的整数时,应使用.equals()(或者最好还是将==与原始整数一起使用,除非有使用对象类型的良好情况.)

Just to re-iterate - when comparing integers like this in all real world scenarios, then .equals() should be used (or preferably still, == with primitive integers unless there's a good case for using the object type.)

这篇关于Java Integer自动自动装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆