包装类的缓存及自动装箱、拆箱

it2022-05-05  136

我们知道Java有八个基础类型,同时为每个基础类型提供了对应的包装类型,对应关系如下:

基础类型包装类型byteIntegercharCharactershortShortintIntegerlongLongfloatFloatdoubleDoublebooleanBoolean

什么是自动装箱/拆箱?

自动装箱:将基本类型的变量赋值给对应的包装类 自动拆箱:将包装类对象直接赋值给对应的基础类型变量

什么情况下会触发自动装箱?

基本类型赋值给包装类型时会触发自动装箱,调用包装类型的valueOf()方法。 Integer i = 100; // 上面的代码相当于: Integer i = Integer.valueOf(100);

什么情况下会触发自动拆箱?

当包装类参与运算时触发自动拆箱,调用对应的xxxValue()方法。包装类与基本类型比较、或赋值给基本类型时,触发自动拆箱 Integer i = 100; i ++; // i参与运算,自动拆箱 int j = i;// i赋值给基本类型,自动拆箱

解释了自动装箱、拆箱,我们来看一道经典面试题:

Integer i01 = 59;// 相当于 Integer.valueOf(59); int i02 = 59; Integer i03 = Integer.valueOf(59); Integer i04 = new Integer(59); System.out.println(i01 == i02); System.out.println(i01 == i03); System.out.println(i03 == i04); System.out.println(i02 == i04);

我们一起分析一下: i01 == i02,因为i02为基本类型,i01自动拆箱,应该返回true; i01和i03为两个对象,应该返回false;(这个结论是错误的,后面会解释) i03、i04为两个不同对象,应该返回false; i02 == i04,i04自动拆箱,应该返回true; 但实际运行结果是:

true true false true

为什么i01 == i03 会返回true呢?我们知道引用类型“==”比较的是对象的地址即两者是不是同一个对象,这两个为什么会是同一个对象?我们来看一下Integer源码(JDK8)中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); } private static class IntegerCache { static final int low = -128;// 缓存池最小值,默认-128 static final int high;// 缓存池最大值,默认127 static final Integer cache[];// 缓存数组 static { int h = 127; //可通过修改参数"java.lang.Integer.IntegerCache.high"来设置缓存池的最大值 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 // MAX_VALUE = 0x7fffffff,即(2^32)-1 // 取较小值:为什么Integer.MAX_VALUE - (-low) - 1? h = Math.min(i, Integer.MAX_VALUE - (-low) - 1); } catch (NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. // 如果不能转换成int类型,就忽略它 } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // 断言有什么作用? assert Integer.IntegerCache.high >= 127; } private IntegerCache() {} }

valueOf(int i)方法先判断了变量i的值是否在[IntegerCache.low,IntegerCache.high]范围内: 如果在范围内,则返回的IntegerCache.cache[i + (-IntegerCache.low)]; 不在范围内则返回 new Integer(i); 通过IntegerCache内部类的源码我们得知,默认情况下在[-128,127]会被直接放到缓存中,创建在这个范围内的包装类型时会直接返回创建好的对象,并不会重新创建对象。这就是为什么i01 == i03了。 那为什么i04!=i03呢?i04直接调用了构造方法,返回的新建的对象,并不是从缓存中得到的,所以i04和i03不相等。

private final int value; public Integer(int value) { this.value = value; }

包装类的缓存

通过查看包装类源码,我们发现Java为了在自动装箱时避免每次去创建包装类型,采用了缓存技术。即在类加载时,初始化一定数量的常用数据对象(即常说的热点数据),放入缓存中,等到使用时直接命中缓存,减少资源浪费。Java提供的8种基本数据类型,除了float和double外,都采用了缓存机制。其实原因也很简单,因为浮点型数据,热点数据并不好确定,故并未采用。 各包装类型缓存范围如下:

包装类型缓存值Character0~127Byte,Short,Integer,Long-128 到 127Booleantrue,false

拓展

为什么是Integer.MAX_VALUE - (-low) - 1? // MAX_VALUE = 0x7fffffff,即(2^32)-1 // 取较小值:为什么Integer.MAX_VALUE - (-low) - 1? h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);

因为缓存的下限是-128,程序中已经写死,不能用过配置修改,缓存采用数组来存放需要缓存的Integer对象,java中数组最大长度 = int的最大值,int占用32位,最大值为(2^32)-1即2147483647,所以 h - low <= MAX_VALUE - 1,由此得出h的最大值为Integer.MAX_VALUE - (-low) - 1。 2. assert断言 assert格式: 1)assert [boolean 表达式] 如果[boolean表达式]为true,则程序继续执行。 如果为false,则程序抛出AssertionError,并终止执行。 2)assert[boolean 表达式 : 错误表达式 (日志)] 如果[boolean表达式]为true,则程序继续执行。 如果为false,则程序抛出java.lang.AssertionError,输出[错误信息]。

// 断言有什么作用? // 由assert的语义可知,此处保证IntegerCache.high最小值为127。 assert Integer.IntegerCache.high >= 127; **疑问:**Integer缓存的bug? 在网上看到一篇文章Integer中IntegerCache使用及分析,文章末尾提到了这段代码: public static void main(String[] args) throws Exception { Class<?> clazz = Integer.class.getDeclaredClasses()[0]; Field field = clazz.getDeclaredField("cache"); field.setAccessible(true); Integer[] cache = (Integer[]) field.get(clazz); cache[132] = cache[133]; int a = 2; int b = a + a; System.out.printf("%d+%d=%d", a, a, b); System.out.println(); System.out.println(a + "+" + a + "=" + b); }

查看printf方法源码发现方法形参为Object对象类型,而入参为int基本类型,猜测发生自动装箱,下面我们写一段代码继续验证:

public static void main(String[] args) { try { int a = 2; int b = 4; Class<?> clazz = Integer.class.getDeclaredClasses()[0]; Field field = clazz.getDeclaredField("cache"); field.setAccessible(true); Integer[] cache = (Integer[]) field.get(clazz); cache[132] = cache[133]; Object obj1 = a; Object obj2 = b; System.out.println(obj1); System.out.println(obj2); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }

通过断点及输出结果我们发现int转为Object类型时发生了自动装箱,而4在[-128,127]范围内,多态情况下Object.toString调用了Integer的toString方法,输出了缓存中的5。(破获大案/笑哭)


最新回复(0)