1、前言
之前见过一道笔试题,如下
public static void main(String[] args){
Integer a1 = new Integer(3);
Integer a2 = new Integer(3);
System.out.println(a1 == a2);
Integer b1 = Integer.valueOf("3");
Integer b2 = Integer.valueOf("3");
System.out.println(b1 == b2);
Integer c1 = Integer.valueOf("300");
Integer c2 = Integer.valueOf("300");
System.out.println(c1 == c2);
}
问输出结果分别是多少?
对于第一个输出肯定是false,因为创建了两个对象,通过 == 比较的是对象的地址值,显然两个不同的对象地址值也是不同的
对于第二第三个,究竟是false还是true,这里先不给出答案,下面就来看下Integer的valueOf方法究竟是怎么执行的
2、valueOf
来看下valueOf方法的源码
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
可以发现,如果传入的字符串,那么会先通过parseInt转换为int类型,再通过valueOf方法来得到Integer类(这里parseInt方法的第二个参数是进制的意思,这里表示十进制)
public static Integer valueOf(int i) {
//IntegerCache.low = -128
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里先做了一个判断,大概意思就是:如果i的值在某个区间内,那么回去IntegerCache.cache这个数组里面去取值。其实看到这里大概就能知道,Integer里有一个cache数组,存储了一些提前缓存好的数据,当你传入的i满足if条件里的区间,那么就是去这个cache数组里面取对应的Integer对象。
下面来看下这个cache数组如何初始化
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() {}
}
在Integer类里有个内部类IntegerCache,他被设计成单例模式,其中通过静态代码块来完成cache数组的初始化,可以看到low固定是-128,而high值则可以根据配置文件来改变(这里直接考虑默认的情况),默认情况值是127,之后通过一个for循环来初始化cache数组内的Integer对象。
即默认情况下,cache数组存储了从-128到127的Integer对象
3、总结
现在看回开头的问题就知道答案应该如下
public static void main(String[] args){
Integer a1 = new Integer(3);
Integer a2 = new Integer(3);
System.out.println(a1 == a2);//false
Integer b1 = Integer.valueOf("3");
Integer b2 = Integer.valueOf("3");
System.out.println(b1 == b2);//true
Integer c1 = Integer.valueOf("300");
Integer c2 = Integer.valueOf("300");
System.out.println(c1 == c2);//false
}
当值为3的时候,很明显是在缓存的范围,此时通过cache数组来获取Integer对象,获取的对象是一样的,而300超出缓存范围,则各自创建Integer对象
在Short以及Long包装类中也有类似的cache数组,只需类比Integer的设计即可