java装箱拆箱

装箱:将基本类型转换为包装类。

integer i1 = 10;//自动装箱

valueOf()方法,装箱


显式装箱

Integer i2 = (Integer)10;//显式装箱
Integer i3 = new Integer(10);

i3放在栈上, new Integer(10)放在堆上。i3存储的是new Integer(10)的地址。



在-128 - 127范围内,将数据放入缓存中,不再这个范围内,new 一个新的对象。

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);

}

Integer i4 = 128;
Integer i5= 128;
System.out.println(i4==i5);//false

System.out.println(i4.equals(i5));//true


拆箱:将包装类转换成基本类型。一般来说调用intValue()、doubleValue()方法等。

int ii1 = i1;    //拆箱



int ii2 = (int)i1;//显式拆箱.


总结:

自动装箱时编译器调用valueOf将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。自动装箱是将boolean值转换成Boolean对象,byte值转换成Byte对象,char转换成Character对象,float值转换成Float对象,int转换成Integer,long转换成Long,short转换成Short,自动拆箱则是相反的操作。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值