Java中 Interger 的自动装箱

先来看下面一个题分别输出什么?

 

 1      Integer a1 = new Integer(127);   
 2 
 3      Integer a2 = new Integer(127);   
 4 
 5      System.out.println(a1 == a2);   
 6 
 7 
 8       Integer b1 = new Integer(128);   
 9          
10       Integer b2 = new Integer(128);   
11 
12       System.out.println(b1 == b2);  

很多人会说,这太简单了,两个肯定都是false,因为它们都是不同的对象,用==比较的时候肯定是false。

的确,恭喜你答对了!

现在我们再来看下面这道题

 

 1      Integer a1 = 127;   
 2 
 3      Integer a2 = 127;   
 4 
 5      System.out.println(a1 == a2);   
 6 
 7       Integer b1 = 128;   
 8  
 9       Integer b2 = 128;   
10 
11       System.out.println(b1 == b2); 

不要那么急着回答的,要仔细想好了,如果你回答的和上面一样,那么请仔细看下面的解释!

因为这里涉及到了Java的自动装箱,所以我们先介绍下自动装箱的概念

当我们在代码中 以Integer i=15这样的方式定义时 Java编译器在编译时,在class中加入了Integer.valueOf()方法。也就相当于

Integer i = Integer.valueOf(15)  这就是自动装箱; 同时为了降低自动装箱对性能的影响,Java在执行包装类的自动装箱功能时,对于

-128到127之间的整数被装箱为Interger对象后,该对象会被另外一个对该整数进行自动装箱的操作重复使用,也就是说多次对同一个-128

到127范围内的整数进行Integer装箱的操作,使用的都是第一次进行装箱操作时生成的对象,所以第一个答案就变成了 true。第二个当然还是false了。

现在相信大家对Interger的自动装箱能有了一个简单的认识!那么我们何时应该使用自动装箱呢?

官方的建议:

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, 
for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between
primitive types and reference types, but they do not eliminate it.

 

转载于:https://www.cnblogs.com/heshan664754022/archive/2013/03/27/2985304.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值