Integer包装类
研究问题
Integer类中的127和128
一、以下代码输出是什么?
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d= 128;
System.out.println(a == b);
System.out.println(c == d);
}
二、输出结果
true
false
三、结果分析
在Integer a = 127中,发生了自动装箱,会调用Integer.valueOf(a),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);
}
可以看出:
1.在Integer包装类的数值范围为[-128,127]时,将数装入到名为cache的数组中,放在下标为i+[-(128)]的位置,i属于[-128,127],那么cache数组的范围为[0,255];
2.当数值不在[-128,127]范围时,就新建一个Integer对象。
故:在上述代码中,a和b是相等的,存放在cache数组的cache[255]位置,而c和d是不同的对象,不相等。