1.大纲概述
Int 整型为java八大基础类型之一,Integer是它的包装器类型;int的默认值为0,而Integer的默认值为null。
128陷阱:指 Integer类封装的数字在[-128,127]范围内比较可以相等,超过此范围不能相等的现象。如下为代码示例:
public static void main(String[] args)
{Integer a = 127;Integer b = 127;Integer c = 128;Integer d = 128;Integer e= -129;Integer f= -129;System.out.println(a==b);System.out.println(c==d);System.out.println(e==f);
}
输出:
true
false
false
自动装箱:int到Integer的变换称为装箱(自动将基本数据类型转换为包装器类型),当有一个Integer对象赋予给int将会自动拆箱,而Integer的自动装箱要求数据介于-128~127之间。
Integer a=Integer.valueOf(100);
自动拆箱:Integer到Int的变换称为拆箱(自动将包装器类型转换为基本数据类型)
int d=c.intValue()*1-100;
2、代码分析
IntegerCache.low 和IntegerCache.high是“128陷阱”的关键。java对在-128~127之间的Integer的值,用原生数据类型int,会在内存里供重用,也就是说这之间的Integer值进行 == 比较时只是进行int原生数据类型数值比较,超出-128~127的范围,进行 == 比较时是进行地址比较。(引用类型用 == 比较,是对他们的地址进行比较)
Integer 自动装箱代码:
public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint 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_VALUEh = 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() {}}
用两个等号==相比较时,比较的是valueOf的返回值,可以看出,IntegerCache.low 和IntegerCache.high是“128陷阱”的关键。当int i超过某个范围时,返回一个新的对象,即
return new Integer(i);
否则,如果i在约束的范围内(范围很可能时我们上面提到的[-128,127]),返回某个固定地址的值。即
return IntegerCache.cache[i + (-IntegerCache.low)];
IntegerCache.low默认是-128;IntegerCache.high默认是127。
如果传入的 i 在IntegerCache.low 和IntegerCache.high之间,那就尝试看前面的缓存中有没有打过包的相同的值,如果有就直接返回,否则就新创建一个Integer实例,此时地址会改变,当进行 ==的比较时会返回false.