問題描述
這里它們是同一個實(shí)例:
Here they are the same instance:
Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2); // outputs "true"
但這里它們是不同的實(shí)例:
But here they are different instances:
Integer integer1 = 128;
Integer integer2 = 128;
System.out.println(integer1 == integer2); // outputs "false"
為什么包裝對象只在值 127 內(nèi)共享同一個實(shí)例?
Why do the wrapper objects share the same instance only within the value 127?
推薦答案
因?yàn)樗怯蒍ava語言規(guī)范指定的.
Because it's specified by Java Language Specification.
JLS 5.1.7拳擊轉(zhuǎn)換:
如果被裝箱的值 p
是 true
、false
、byte
或 u0000
到 u007f
范圍內(nèi)的字符,或介于 - 之間的 int
或 short
數(shù)字128和127(含),則令r1
和r2
為任意兩次裝箱轉(zhuǎn)換的結(jié)果p
.r1 == r2
總是如此.
If the value
p
being boxed istrue
,false
, abyte
, or achar
in the rangeu0000
tou007f
, or anint
orshort
number between -128 and 127 (inclusive), then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.
理想情況下,對給定的原始值 p
進(jìn)行裝箱,總是會產(chǎn)生相同的引用.在實(shí)踐中,使用現(xiàn)有的實(shí)現(xiàn)技術(shù)這可能是不可行的.上述規(guī)則是一種務(wù)實(shí)的妥協(xié).上面的最后一個條款要求某些常見的值總是被裝箱到無法區(qū)分的對象中.實(shí)現(xiàn)可能會懶惰地或急切地緩存這些.對于其他值,此公式不允許程序員對裝箱值的身份進(jìn)行任何假設(shè).這將允許(但不要求)共享部分或全部這些引用.
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.
這可確保在大多數(shù)常見情況下,行為將是所需的行為,而不會造成過度的性能損失,尤其是在小型設(shè)備上.例如,內(nèi)存限制較少的實(shí)現(xiàn)可能緩存所有 char
和 short
值,以及 int
和 long
值在 -32K 到 +32K 的范圍內(nèi).
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 char
and short
values, as well as int
and long
values in the range of -32K to +32K.
這篇關(guān)于整數(shù)包裝對象僅在值 127 內(nèi)共享相同的實(shí)例?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!