有如下题:
public static void main(String[] args) {
Integer t1 = 101;
int t2= 101;
Integer t3 = Integer.valueOf(101);
Integer t4 = new Integer(101);
System.out.println(t4==t3);
}
结果为:false
Integer.valueOf(n);和new Integer(n)的区别如下:
首先看Integer.valueOf的源码:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
其中IntegerCache的源代码:
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
可以看到在IntegerCache中已经初始化了cache数组。所以,在任何条件下,new Integer()返回的永远是不同的对象。对但是对Integer.valueOf()方法来说,当整数范围在-128<i<=127
时,Integer.valueOf返回的是同一个对象。