自动装箱的面试题踩到的坑

本文通过一道面试题揭示了Java中自动装箱的潜在陷阱。Integer的自动装箱并非总是创建新对象,而是利用IntegerCache缓存了-128到127之间的值。超出这个范围的装箱操作则会新建对象,导致一些意外的相等判断结果。其他类型的装箱,如Byte、Float、Double没有类似缓存,而Short、Long和Character的缓存范围各有不同。
摘要由CSDN通过智能技术生成
Integer i1 = new Integer(32);
Integer i2 = new Integer(32);
System.out.println(i1 == i2);							//false
System.out.println(i1.equals(i2));						//true

		
Integer i3 = new Integer(132);
Integer i4 = new Integer(132);
System.out.println(i3 == i4);							//false
System.out.println(i3.equals(i4));						//true


Integer i5 = 32;
Integer i6 = 32;
System.out.println(i5 == i6);							//true
System.out.println(i5.equals(i6));						//true


Integer i7 = 132;
Integer i8 = 132;
System.out.println(i7 == i8);							//false
System.out.println(i7.equals(i8));						//true

以前只知道装箱和拆箱在JDK能自动了,没研究过代码,这两天看面试题的时候,踩到了雷,如上第三段代码的i5 == i6的判断还是想当然的填了个false,测试结果发现是true。

不知道原因,查了下源码

public static Integer valueOf(int i){
      if(i>=IntegerCache.low && i<=Integ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值