Java中奇怪的整数拳击 [英] Weird Integer boxing in Java

查看:81
本文介绍了Java中奇怪的整数拳击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看到类似的代码:

public class Scratch
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);

        Integer c = 100, d = 100;
        System.out.println(c == d);
    }
}

运行时,这段代码将打印出来:

When ran, this block of code will print out:

false
true

我理解为什么第一个是 false :因为这两个对象是单独的对象,所以 == 比较引用。但我无法弄清楚,为什么第二个语句返回 true ?当Integer的值在一定范围内时,是否会出现一些奇怪的自动装箱规则?这里发生了什么?

I understand why the first is false: because the two objects are separate objects, so the == compares the references. But I can't figure out, why is the second statement returning true? Is there some strange autoboxing rule that kicks in when an Integer's value is in a certain range? What's going on here?

推荐答案

true 行实际上是由语言规范。来自第5.1.7节

The true line is actually guaranteed by the language specification. From section 5.1.7:


如果盒装的值为真,
false,一个字节,$ b范围内的char $ b \ u0000到\ u007f,或-128到127之间的int或short
数,然后让
r1和r2为p的任意两个
拳击转换的结果。在r1 == r2的情况下总是

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.

讨论继续进行,暗示尽管你的第二行是输出是有保证的,第一个不是(参见下面引用的最后一段):

The discussion goes on, suggesting that although your second line of output is guaranteed, the first isn't (see the last paragraph quoted below):


理想情况下,装箱给定的原语
值p,总是会产生
相同的引用。实际上,使用现有的
实现技术,这个
可能是不可行的。上面的规则
是务实的妥协。上面的
最后一个条款要求
某些常见值总是被装箱成
到无法区分的对象中。
实现可以缓存这些,懒得
或急切。

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly.

对于其他值,此公式
不允许对$ b的任何假设
程序员的盒装值的$ b标识。这将允许
(但不要求)共享一些或
所有这些引用。

For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

这确保了最常见的
在这种情况下,行为将是
所需的行为,而不会产生过高的
性能损失,尤其是在
小型设备上。例如,较少内存限制的
实现可以缓存所有字符和短路,
以及
范围内的整数和长整数-32K - + 32K。

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all characters and shorts, as well as integers and longs in the range of -32K - +32K.

这篇关于Java中奇怪的整数拳击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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