今天遇到一个问题,下面是问题代码:
public class TestJavaCandy {
public static void main(String[] args) {
Integer e = -129;
Integer f = -129;
System.out.println(e == f);
}
}
输出:false
如果把 e 和 f 的值调整为-128~127之内,那么,输出为true;如果把 e 和 f 的值调整为超过127,那么输出为false。
请问这是为什么。
------解决思路----------------------
在这个范围内,系统会自动为这范围内的每一个整数缓存对象,这范围的每一个相同的数字对应的Integer对象所对应的引用都是相等的,因为指向的对象都是一个,而这范围之外的就没有这种缓存。也就和正常的引用一样,因为指向的是不同的对象,所以不相等,这样做的原因是为了加快系统效率。
------解决思路----------------------
Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS.
------解决思路----------------------
这个问题出现很多次了,Integer缓存了-128~127之间的数,这是在类加载期间就完成的。以后需要的时候直接指向它就可以了,省去了构造对象的开支,提高了效率。
------解决思路----------------------
Integer 源码
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer 缓存-128 ~ 127 之间的数字,范围外的就只能去new了