详解Java的自动装箱(autoboxing))与拆箱(unboxing)

Java的包装类型

对于Java的基本类型都会有默认值,如果数据本身就不存在,直接使用默认值看起来就不那么合适。此时,Java设计的基本数据类型封装成对象的包装类型就能派上用场。

  • 装箱拆箱的类型有哪些?如下图红色框选中类
    在这里插入图片描述
  • 基本数据类型与包装类的对应关系
基本类型 包装类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

什么是自动装箱拆箱

以下代码就是自动装箱拆箱的过程。

public class Test {
    public static void main(String[] args) {
        //自动装箱
        Integer hairCounts = 10000;//这里在笔者编辑器中属于第6行
        //自动拆箱
        int hairCountsLeft = hairCounts;//这里在笔者编辑器中属于第8行
    }
}

整个过程都是自动执行,使用IDEA的Show Bytecode,查看字节码

在这里插入图片描述

  • 找到关键第6行
    在这里插入图片描述
    系统自动执行了,
Integer hairCounts = Integer.valueOf(10000);

这就是自动装箱的过程

找到关键的第8行
在这里插入图片描述
系统自动执行了

int hairCountsLeft = hairCounts.intValue();

这就是自动拆箱的过程。因为会有自动拆箱的过程所以一定要注意对象是否为空,否则容易造成java.lang.NullPointerException

包装类型的缓存

打开Integer.java的valueOf(),如果i在[IntegerCache.low,IntegerCache.high]区间内则使用的是cache,否则重新创建对象。

/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

包装类型缓存区间如下:
Boolean:使用静态final,就会返回静态值
Byte:-128~127
Short:-128~127
Character:0~127
Long:-128~127
Integer:-128~127
Float和Double因为特殊性设置缓存意义不大,Float和Double的初始方法如下

public static Double valueOf(double d) {
    return new Double(d);
}

public static Float valueOf(float f) {
    return new Float(f);
}

如果所使用的包装类的值在这个缓存区间内,就会直接复用已有对象,在缓存区间之外的数值会重新在堆上产生。所以在判断是否相等时不要用“==”,用equals

在这里插入图片描述

Integer是唯一一个可以修改缓存范围的包装类。在VM options加入参数: -XX:AutoBoxCacheMax=12000即将缓存区间的最大值改为12000.
在这里插入图片描述
在这里插入图片描述

原创文章 29 获赞 41 访问量 965

猜你喜欢

转载自blog.csdn.net/lovesunren/article/details/105591222