首先一道小题送上!
Integer中有个静态内部类 IntegerCache ,里面有个cache[],也就是Integer常量池 大小为一个字节(-128-127).
源码送上(jdk1.8.0_101)
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() {}
}
A 选项 体现了自动拆箱的特性。 所以两者相等
B 选项 .valueOf()方法中 在一个字节之内的数都会返回一个常量池中的对象 所以相等
c 选项 因为有new的关系所以会开辟一块新的内存存放59,两者地址不同 所以不等
D 选项 两者地址不一样应该是错的 ,但是正相反 Integer 引用类型 int 是基本类型 integer会自动拆箱,调用intValue的
方法,返回int类型 两个基本类型相比 值相等 必然相等。