Java中自动装箱、拆箱引起的问题

一、装箱概念

Integer a = 10;

.实际Integer是一个引用类型,并不是基本类型,引用类型严格意义是要这么写的

integer a = new integer(10)

说明:java5以后实现了自动装箱功能,会自动根据数值创建对应的 Integer对象,这就是装箱。
二、拆箱
把integer对象类型变为int基本数据类型就是拆箱。

Integer i = 10;  //装箱
int n = i;   //拆箱

三、实现过程
装箱过程:自动调用integer的Valueof(int)方法。
拆箱过程:自动调动integer的IntValue方法。
四、Valueof(int)源码分析
java装箱过程中如果值在-128至127之间,取得是cache里面同一个对象,不会从新再New一个Integer对象,超过此区间才相当于integer a = new integer(10)

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

五、例子
说明:
1、当 ""运算符的两个操作数都是## 标题包装器类型的引用,则是比较指向的是否是同一个对象。
2、当 "
"运算符的两个操作数其中有一个参与运算,==两边的对象自动触发拆箱变为Int,比较的就是int数值了。
3、当是equals时,两边即使有参与运算,也不会触发拆箱,也不会改变Integer类型。

public class Main {
    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
  
System.out.println(c==d);//c和d在-128和127之间,所以是同一个对象,返回True
System.out.println(e==f);//不在-128和127之间,每次都会New Integer,返回false
System.out.println(c==(a+b));//任何一方有加减乘除运算,==就是值的比较,不是对象比较,返回True
System.out.println(c.equals(a+b));//对于包装器类型,equals方法并不会进行类型转换。返回True
System.out.println(g==(a+b));//一方参与运算,自动拆箱,变成同一个基本类型。返回True
System.out.println(g.equals(a+b));//a+b是integer类型,g是Long类型,返回false
System.out.println(g.equals(a+h));//a+h运算变为Long类型,和g类型一直,返回True
    }
}

六、基本类型对应的包装类型
在这里插入图片描述
参考资料:https://www.cnblogs.com/dolphin0520/p/3780005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值