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;
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。乍一看这让我觉得很奇怪,它们作为参考应该是不同的。我可以发现,如果我将相同的 byte 值(-128 到 127)传递给 i3 和 i4,它们作为引用将始终相等,但任何其他值都会产生不同的结果。
我无法解释这一点,您能给我一些文档或提供一些有用的见解吗?
谢谢
Hey I am trying to understand the following code snippet.
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");
}
This method runs all of the println instructions. That is i1 != i2 is true, but i3 == i4. At first glance this strikes me as strange, they should be all different as references. I can figure out that if I pass the same byte value (-128 to 127) to i3 and i4 they will be always equal as references, but any other value will yield them as different.
I can't explain this, can you point me to some documentation or give some helpful insights?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
int
值自动装箱到Integer
对象将使用通用值的缓存(如您所识别的那样)。这是在 JLS §5.1.7 中指定的拳击转换:请注意,这仅在语言为您自动装箱值或时应用当您使用
Integer 时.valueOf()
。使用new Integer( int)
将总是生成一个新的Integer
对象。小提示:JVM 实现也可以自由缓存这些范围之外的值,因为没有指定相反的情况。然而,我还没有看到这样的实现。
Autoboxing
int
values toInteger
objects will use a cache for common values (as you've identified them). This is specified in the JLS at §5.1.7 Boxing Conversion:Note that this will only be applied when the language auto-boxes a value for you or when you use
Integer.valueOf()
. Usingnew Integer(int)
will always produce a newInteger
object.Minor hint: a JVM implementation is free to cache values outside of those ranges as well, because the opposite is not specified. I've not yet seen such an implementation, however.
Java 在 -128 到 128 之间保留一个 Integer 池。如果您使用此范围之外的 Integer,则会创建新的 Integer 对象。这就是解释。
你可以在Java源代码中看到它:
Java keeps a pool of Integer between -128 and 128. If you use Integer outside of this range, new Integer objects are created. That's the explanation.
Here you can see it in the Java source code:
从 -128 到 127 的整数被包装到固定对象中。这就是为什么你得到 i3 == i4。
Integers from -128 to 127 are wrapped into fixed objects. That's why you get i3 == i4.