自动封箱和拆箱

Integer 中

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

  

如果没有设置IntegerCache.high的值,默认为127,也就是说值在-128~127之间,返回的都是同一个对象。
  1. Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
    System.out.println(f1 == f2);
    System.out.println(f3 == f4);
输出结果是:
  1. true
  2. false
Long、Byte、Short同理。
Boolean中
 
   public static Boolean valueOf(boolean b) {
     return (b ? TRUE : FALSE);
   }
Character中
  
public static Character valueOf(char c) {
    if (c <= 127) { // must cache
        return CharacterCache.cache[(int)c];
    }
    return new Character(c);
}    
Double中
  1. public static Double valueOf(double d) {
      return new Double(d);
    }
     
对于任何的duoble类型的数据,每次都是从新装箱,生一个新的对象;Float类型同理。
  1. 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);//不用解释了把,关于Integer中写的很清楚-128~127都是自动装箱成同一个对象了
    System.out.println(e==f);//看Integer中解释
    System.out.println(c==(a+b));//因为+所有a和b自动拆箱,会各自调用IntValue()方法,得到值后会在调用Integer.valueOf
    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));//因h是long类型,a则自动向上转型为Long
    }
输出结果:
  1. true
  2. false
  3. true
  4. true
  5. true
  6. false
  7. true
  8. true

转载于:https://www.cnblogs.com/woniu4/p/4765754.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值