Java中奇怪的整数装箱 [英] Weird Integer boxing in Java

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

问题描述

我刚刚看到类似这样的代码:

I just saw code similar to this:

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?当整数的值在某个范围内时,是否有一些奇怪的自动装箱规则?这是怎么回事?

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:

如果被装箱的值 p 为真,false,一个字节,范围内的一个字符u0000 到 u007f,或 int 或 short-128 到 127 之间的数字,然后让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.

对于其他值,此公式不允许任何关于盒装值的标识程序员的部分.这将允许(但不要求)分享一些或所有这些参考资料.

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天全站免登陆