这里它们是同一个实例:
Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2); // outputs "true"
但这里它们是不同的实例:
Integer integer1 = 128;
Integer integer2 = 128;
System.out.println(integer1 == integer2); // outputs "false"
为什么包装对象只在值 127 内共享同一个实例?
最佳答案
因为它是由 Java 语言规范指定的。
If the value
p
being boxed istrue
,false
, abyte
, or achar
in the range\u0000
to\u007f
, or anint
orshort
number between -128 and 127 (inclusive), then letr<sub>1</sub>
andr<sub>2</sub>
be the results of any two boxing conversions ofp
. It is always the case thatr<sub>1</sub> == r<sub>2</sub>
.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.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
andshort
values, as well asint
andlong
values in the range of -32K to +32K.
关于java - 整数包装对象仅在值 127 内共享相同的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5117132/