一:什么是自动拆箱、自动装箱
简单来说,由包装类型自动转化为基本类型是自动拆箱,由基本类型转化为包装类型是自动装箱
以int和Integer为例
Integer i=86; jvm底层就会为我们自动装箱 Integer i=Integer.valueOf(86);
int k=i;jvm底层就会为我们自动拆箱 int k=i.intValue();
其中valueOf是Integer的静态方法,intValue是实例方法
我们来看看intValue这个方法
public int intValue() { return value; }
很简单,返回值就可以了
二:Integer的缓存值
这个就关系到Integer的静态方法valueOf(int i)了
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
里面的意思是 如果i大于等于-128小于等于127(这个其实暂定)的话,就把Integer里面的 内部类IntegerCache的静态变量cache数组里面的值返回去
否则就会新建一个Integer对象,来我们先看看这个内部类IntegerCache
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() {} }
很明显low就是-128,但是high需要比较一下才会确定哪个,不过一般都是127,然后把这些Integer对象都放进一个静态Integer数组,因为-128~127初始化实在静态代码块里面,只要内部类IntegerCache一加载,就会初始化,而Integer i=86;就会变成Integer i=Integer.valueOf(86);而valueOf方法又会调用那个内部类,环环相扣。
这就是Integer缓存值