Integer i1 = 127; Integer i2 = 127; System.out.println(i1==i2); //true Integer i3 = 128; Integer i4 = 128; System.out.println(i3==i4);//false System.out.println("Byte"); Byte b1 = 127; Byte b2 = 127; System.out.println(b1==b2); //true Byte b3 = -128; Byte b4 = -128; System.out.println(b3==b4); //true System.out.println("Short"); Short s1 = 127; Short s2 = 127; System.out.println(s1==s2); //true Short s3 = 128; Short s4 = 128; System.out.println(s3==s4);//false System.out.println("Long"); Long l1 = Long.valueOf(127); Long l2 = Long.valueOf(127); System.out.println(l1==l2); //true Long l3 = Long.valueOf(128); Long l4 = Long.valueOf(128); System.out.println(l3==l4);//false
###1.Integer的装箱缓存
Integer i1 = 127 //实际上 等于 Integer i1 = Integer .valueOf(127) 自动装箱
代码跟进
public static Integer valueOf(int i) { //首先可以看到对参数i进行了范围判断 //low = -128; int h = 127 //在这个范围内 返回 IntegerCache.cache[i] if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
以上可以知道 当 valueOf(i) i的范围在 -128 ~ 127之间时,返回的是 cache数组的 i + (-IntegerCache.low) 对应下标元素
IntegerCache 是什么呢 根据代码可以知道是内部类
cache 是Integer的数组
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() {} }
看这行代码 for循环给cache动态数组元素赋值
cache = new Integer[(high - low) + 1]; //j = -128 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;
再看一个 LongCache 其他都一样
private static class LongCache { private LongCache(){} static final Long cache[] = new Long[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Long(i - 128); } }