最常见的Integer用法:
Integer i = Integer.valueOf(10);
在下面的比较中:
Integer i = Integer.valueOf(10);
Integer j = 10;
Integer k = new Integer(10);
System.out.println(j == i); // true
System.out.println(j == k); // false
从运行结果中可以知道,Integer.valueOf() 并没有创建新的对象。
从源码中去探索:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache.low代表integer缓存最小值,IntegerCache.high代表integer缓存最大值,return之前做了一个判断,判断传进来的值是否是在两值之间。
在往深一层:
private static class IntegerCache {
static final int low = -128; // 缓存最小值
static final int high; // 缓存最大值(没有默认值,可自定义,上限是2的31次方-1)
static final Integer cache[]; // 缓存值数组
static {
// high value may be configured by property
int h = 127; // 缓存最大值默认是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() {}
}
判断如果在最大最小值之前则直接取缓存数组对应下标的值,注意数组下标要加128,因为从-128开始创建对象。
既然默认值是从-128到127,那么再回到开始:
Integer i = Integer.valueOf(1000);
Integer j = 1000;
System.out.println(j == i); // false