且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中奇怪的整数装箱

更新时间:2023-09-18 09:30:22

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.