转载:Java的装箱和拆箱,你掌握到了第几层

Java装箱与对象复用
本文探讨了Java中Integer等基本类型的装箱过程及对象复用机制,并通过实例展示了不同情况下的对象比较结果。

原文地址

总结

  1. Integer是采用valueOf方法进行装箱的,当取值在[-127,128]之间时,会进行对象复用。Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
  2. Double、FloatvalueOf方法的实现是类似的,这些方法没有进行对象复用。
  3. BooleanvalueOf方法如下:
public static Boolean valueOf(boolean b) {
       return (b ? TRUE : FALSE);
   }
public static final Boolean TRUE = new Boolean(true);

   /** 
    * The Boolean object corresponding to the primitive 
    * value false. 
    */
   public static final Boolean FALSE = new Boolean(false);
复制代码

所以,只要相等,都是同一个对象。

练习题

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);
       System.out.println(e==f);
       System.out.println(c==(a+b));
       System.out.println(c.equals(a+b));
       System.out.println(g==(a+b));
       System.out.println(g.equals(a+b));
       System.out.println(g.equals(a+h));
   }
}
复制代码

答案:

true
false
true
true
true
false
true
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值