Java中的装箱与拆箱

    Java中的数据类型有基本数据类型和引用数据类型,基本数据类型都有对应的包装类,以下是基本数据类型对应的字节数、默认值、以及相应的包装器类型。

byte 1字节 0 Byte
char 2字节 Unicode Char
short 2字节 0 Short
int 4字节 0 Integer
long 8字节 0 Long
float 4字节 0.0f Float
double 8字节 0.0d Douoble
boolean   false Boolean

什么是装箱和拆箱?

Integer i=10;//valueOf()   装箱
Integer i2=(Integer)10;//显示装箱
Integer i3=new Integer(20);// new 堆分配
int  i4=i;//intValue()
int i5=(int)i;//显示拆箱

装箱就是将基本数据类型转换为包装器类型,拆箱就是把包装器类型转换为基本数据类型。装箱的时候调用valueOf方法,拆箱时调用的是 基本数据类型+Of方法。

以int和Integer为例

public class TestDemo {
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 129;
        Integer i4 = 129;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

输出结果为:true 

                   false

这表明i1和i2为同一对象,i3和i4指的是不同的对象。接下来看一下Integer的valueOf()的源码。

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

    这表明数值在-128~127之间的数,会返回已存在对象的引用,如果不在这个范围内,则返回一个新的对象。上述的i3和i4大于127,所以输出的结果为false。



猜你喜欢

转载自blog.csdn.net/sinat_37003267/article/details/79771757