自动装箱和自动拆箱

自动装箱和自动拆箱的问题


昨天老师讲了包装类,学习的目标是要理解自动装箱和自动拆箱的原理,老师留了个课后作业,题目如下:

public class demo {
  public static void main(String[] args) {
  Integer a1 = 127;
  Integer a2 = 127;
  Integer b1 = 128;
  Integer b2 = 128;
  System.out.println(a1 == a2); //true
  System.out.println(b1 == b2); //false
  }
 }

 


答案第一个输出的为什么是·true呢?或许你会有这样的疑问,Integer不是包装类嘛,不是应该存在堆内存中嘛,为什么a1 == a2 是true这样,其实这里就包含了自动装箱和自动拆箱的原理。

1.什么是自动装箱?
自动装箱:将基本数据类型自动转成包装类
如 :

Integer a = 127;
//实际上是做了如下操作:
Integer a = Integer.valueOf(127);

 

2.什么是自动拆箱?
自动拆箱:将包装类自动转成基本数据类型
如:

Integer a= 127;
int b = a; //自动拆箱
//实际上是:
Integer a = Integer.valueOf(3);
int b = a.intValue();


我们可以用反编译工具看看是不是这样的,把编译运行后的demo.class文件拖到反编译工具,代码如图:


接下来我们可以查看Integer的valueof的底层源码,注释的意思是:“该方法将始终缓存-128到127范围内的值(包括),并且可能缓存此范围之外的其他值。”

* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}

 

1、a1和a2会进行自动装箱,执行了valueOf函数,它们的值在-128-127]这个范围内,然后会返回 IntegerCache.cache[i + (-IntegerCache.low)],也就是写入缓存,a1和a2引用到了同一个Integer对象,所以它们肯定是相等的。

2、b3和b4也进行自动装箱,执行了valueOf函数,它们的值大于128,所以会执行new Integer(128),也就是说它们会分别创建两个不同的对象,所以它们肯定不等。

由此我们可以得知结果了,步骤其实不难理解,就只是进行了隐式装箱,然后查看Integer的valueOf方法的源码就清楚了。

posted @ 2019-07-27 11:15  Larva_我在呢  阅读(394)  评论(0编辑  收藏  举报