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/p/2985304.html