Java基础 | 关于 Integer 和装箱、拆箱

一、关于拆箱和装箱

装箱 就是自动将基本数据类型转换为包装器类型;拆箱 就是自动将包装器类型转换为基本数据类型

基本数据类型 包装器类型
int(4子节) Integer
byte(1子节) Byte
short(2子节) Short
long(8子节) Long
float(4子节) Float
double(8子节) Double
char(2子节) Character
boolean(未定) Boolean

具体是怎么进行装箱的呢?

如果需要生成一个数值的对象,那么只需要调用

Integer a = 100;    //装箱

这个过程就会根据数值创建对应的 Integer 对象这就是装箱

而拆箱呢,直接使用

int b = a;      //拆箱

这个时候就是拆箱

我们用一个例子来反编译一下,看看整个过程调用了那些方法

public class IntegerTest {
    public static void main(String[] args) {
        Integer a = 100;
        int b = a;
    }
}

反编译之后的结果如下:

从反编译的结果可以看到,在装箱的时候,调用了 Integer 的 valueOf(int i) 方法;而在拆箱的时候,则调用了 Integer 的 intValue() 方法

我试了一下其他的一些基本类型

public class IntegerTest {
    public static void main(String[] args) {
        Double d = 200d;
        double f = d;

        Short aa = 1;
        short bb = aa;

        Long l = 10000000l;
        long ll = l;
    }
}

经过反编译

果不其然,都调用了各自包装类型的 valueOf(xxx) 方法和 xxxValue() 方法

因此可以总结一下:

装箱过程就是通过包装器的 valueOf() 方法实现的,而拆箱过程是通过调用包装器的 xxxValue() 方法实现的


二、关于 Integer.valueOf

由于 Integer 的这个方法蕴含着一些密码,因此我们拿源代码来分析一下

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

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() {}
}

通过源码可以看到,在 Interger 的 valueOf 方法中,如果数值在 [-127, 128] 范围的时候,就会去 IntegerCache.cache 这个数组寻找有没有存在的 Integer 对象的引用,如果有,则直接返回对象的引用,如果没有(超过了范围),就新建一个 Integer 对象

这个是 cache 数组中已经存在的对象,只是一部分,数组下标范围为 [0,255],对应数值范围是 [-128,127]


三、相关面试题

1.输出以下结果

Integer a = 100;
Integer b = 100;
Integer a1 = 200;
Integer b1 = 200;
Integer a2 = new Integer(100);

a == b;
a1 == b1;
a == a2;

结果: true、false、false

a 和 b 的数值为100的时候,因为 cache 数组中已经存在对象,因此可以直接取出;

a 和 b 的数值为200时,因为 cache 数组中没有相应的对象,因此只能 new 一个 Integer 对象,此时 a1 和 b1 分别指向不同的对象;

a 和 a2 比较的时候,由于 a 调用 valueOf() 进行自动装箱,而 a2 已经是 Integer 对象,相当于两个不同对象之间的比较,因为地址不同,所以肯定不等

需要注意的是,这整个过程中,都没有用到拆箱的过程,可以通过反编译进行验证


2.输出以下代码运行的结果

Double i1 = 100.0;
Double i2 = 100.0;
Double i3 = 200.0;
Double i4 = 200.0;

i1 == i2
i3 == i4

结果:false、false。

为什么呢?由于 Double 在进行装箱的时候也会调用 valueOf() 这个方法,因此看一下源代码

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

public Double(double value) {
    this.value = value;
}

可以看到,Double 并没有 Integer 的冠军机制,而是直接返回了一个新的 Double 对象,因此以上的四个引用都是指向不同的对象的,所以不同

PS

为什么 Double 类的 valueOf() 方法会采用与 Integer 类的 valueOf() 方法不同的实现呢?

很简单:在某个范围内的整型数值的个数是有限的,而浮点数却不是。

我又查看了其他几种数据类型的 valueOf 源码

其中,Double 和 Float 没有缓存机制,都是直接返回新的对象;Integer、Short、Byte、Character 有缓存机制

3.输出以下代码运行的结果

Boolean b1 = false;
Boolean b2 = false;
Boolean b3 = true;
Boolean b4 = true;

b1 == b2
b3 == b4
b1 == b3

结果:true、true、false

为什么会这样呢?看一下 Boolean 的 valueOf() 的源代码

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

其中的 TRUE 和 FALSE,代表两个静态成员属性

public static final Boolean TRUE = new Boolean(true);

public static final Boolean FALSE = new Boolean(false);

因此可以知道了,每次传入的 true 或 false,都是指向同一个 Boolean 对象,因此他们的引用肯定相同了

4.输出以下代码运行的结果

Integer a = 10;
Integer b = 20;
Integer c = 30;
Integer d = 30;
Integer e = 300;
Integer f = 300;
Integer g = a + b;

c == d;
e == f;
c == g;
c == (a + b);
c.equals(a + b);

结果:true、false、true、true、true

先注意这句话:当 “==”运算符的两个操作数都是 包装器类型的引用,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程)

前两个没什么好说的

第三个:由于运用了算术运算符(+),因此右边的算式在进行计算之前会先调用 intVal() 方法进行拆箱,在进行相加,然后得到的结果30之后,由于前面是 Integer g,因此还会再调用 valueOf() 方法进行装箱。由于此时 cache() 数组中已经有了 30 了,因此直接指向缓存池中的 30 这个 Integer 对象。此时 c == g 比较的还是对象的地址是否相同

第四个:由于右边是 a+b,包含算术运算,因此会调用 intVal() 方法,将左边的 c 进行拆箱,之后又分别对 a 和 b 进行拆箱,即一共调用了三次拆箱过程,最后比较的是数值大小,而不是地址

第五个:equals() 方法会先除非自动拆箱,然后在触发自动装箱。a + b 的时候,会先调用两次 intVal() 进行拆箱,然后再调用 valueOf() 方法进行装箱,此时再用 equals() 方法比较。由于都是 Integer,且数值相等,则返回 true


5.输出以下代码运行的结果

Integer a = 10;
Integer b = 20;
Long g = 30L;
Long h = 20L;

g == (a + b);
g.equals(a + b);
g.equals(a + h);

结果:true、false、true

和上面一样,同样是使用拆箱,但是需要注意的是,Integer 类型调用 Integer.valueOf 进行拆箱,而 Long 类型调用 Long.valueOf 进行拆箱

最后一个结果是 true,因为 a + h 会使小的精度转为大的精度,最终的 30 是 Long 类型的,因此结果是 true


四、参考

深入剖析Java中的装箱和拆箱

猜你喜欢

转载自blog.csdn.net/babycan5/article/details/81942230