/**
* Created by spring on 10/26/13.
*/
public class Test {
public static void main(String args[]){
Integer i_128 = -128;
Integer j_128 = -128;
System.out.println(i_128==j_128);
Integer i_129 = -129;
Integer j_129 = -129;
System.out.println(i_129==j_129);
Integer i128 = 128;
Integer j128 = 128;
System.out.println(i128==j128);
Integer i127 = -127;
Integer j127 = -127;
System.out.println(i127==j127);
}
}
输出:
true
false
false
true
这个原因想必大家都知道,Integer是一个不可变类,所以对一些常用的值(-128--127)进行了缓存,避免对象的频繁创建和销毁。但是从jdk1.5开始这个缓存的范围可以由开发者根据需要自己指定,不过下限还是-128,上限可以修改。jdk的源码如下:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax=<size> option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
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);
}