标签:拆箱 int cache static IntegerCache 127 128 Integer
public
class
Main {
public
static
void
main(String[] args) {
Integer a =
100
;
Integer b =
100
;
Integer c =
128
;
Integer d =
128
;
System.out.println(a==b);
System.out.println(c==d);
}
}
输出: true
false
原因:
public
static
Integer valueOf(
int
i) {
if
(i >= IntegerCache.low && i <= IntegerCache.high)
return
IntegerCache.cache[i + (-IntegerCache.low)];
return
new
Integer(i);
}
可以看到当不满足if
语句中的条件,就会重新创建一个对象返回,那结果必然不相等。继续打开IntegerCache
可以看到
private
static
class
IntegerCache {
static
final
int
low = -
128
;
static
final
int
high;
static
final
Integer cache[];
static
{
// high value may be configured by property
int
h =
127
;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty(
"java.lang.Integer.IntegerCache.high"
);
if
(integerCacheHighPropValue !=
null
) {
try
{
int
i = parseInt(integerCacheHighPropValue);
i = Math.max(i,
127
);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -
1
);
}
catch
( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache =
new
Integer[(high - low) +
1
];
int
j = low;
for
(
int
k =
0
; k < cache.length; k++)
cache[k] =
new
Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert
IntegerCache.high >=
127
;
}
private
IntegerCache() {}
}
在通过valueOf
方法创建Integer
对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache
中已经存在的对象的引用;否则创建一个新的Integer
对象。所以上面代码中a
与b
相等,c
与d
不相等。
标签:拆箱,int,cache,static,IntegerCache,127,128,Integer 来源: https://www.cnblogs.com/JNU-Iot-Longxin/p/15250892.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。