1. 程式人生 > 程式設計 >詳解Java 自動裝箱與自動拆箱

詳解Java 自動裝箱與自動拆箱

包裝器

有些時候,我們需要把類似於int,double這樣的基本資料型別轉成物件,於是設計者就給每一個基本資料型別都配置了一個對應的類,這些類被稱為包裝器。

包裝器整體來說分為四大種:

  1. Number,Number類派生出了Integer,Double,Long,Float,Short,Byte這六個小類分別代表了int,double,long,float,short,byte這六種基本資料型別。
  2. Character,對應的基本資料型別是char。
  3. Void,對應的是關鍵字void,這個類我們會經常在反射中看到,用於表示方法的返回值是void,這裡不再贅述,後面反射章節詳細講解。
  4. Boolean,對應的是基本資料型別boolean。

要記住下面兩點包裝器的特性:

包裝器是不可變的,一旦構造了包裝器,就不允許更改包裝在其中的值。

  1. 包裝器是final定義的,不允許定義它的子類。

自動裝箱和自動拆箱

ArrayList<Integer> list = new ArrayList<>();

list.add(3);

int x = list.get(0);

自動裝箱

當我們新增int值 到一個集合元素全部是Integer的集合中去時候,這個過程發生了什麼?

list.add(3);

//實際上面的程式碼會被編譯器給自動的變成下面的這個程式碼
list.add(Integer.valueOf(3))

編譯器在其中所作的這個事情就叫做自動裝箱。

自動拆箱

當我們取出一個集合中的元素並將這個元素賦給一個int型別的值的時候,這其中又發生了什麼呢?

int x = list.get(0);

//實際上面的程式碼會被編譯器給自動的變成下面的這個程式碼
int x = list.get(0).intValue();

編譯器這其中所作的這個事情就叫做自動拆箱

自動裝箱和自動拆箱中的坑

Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 300;
Integer i4 = 300;

System.out.println(i1 == i2);
System.out.println(i3 == i4);

這是一道經典的面試題,打印出來的結果是:

true
false

為什麼會發生這樣的事情,我們記得自動裝箱的時候會自動呼叫Integer的valueOf方法,我們現在來看一下這個方法的原始碼:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

而這個IntegerCache是什麼呢?

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
      // high value may be configured by property
      int h = 127;
      String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
      if (integerCacheHighPropValue != null) {
        try {
          int i = parseInt(integerCacheHighPropValue);
          i = Math.max(i,127);
          // Maximum array size is Integer.MAX_VALUE
          h = Math.min(i,Integer.MAX_VALUE - (-low) -1);
        } catch( NumberFormatException nfe) {
          // If the property cannot be parsed into an int,ignore it.
        }
      }
      high = h;

      cache = new Integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);

      // range [-128,127] must be interned (JLS7 5.1.7)
      assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

從這2段程式碼可以看出,在通過valueOf方法建立Integer物件的時候,如果數值在[-128,127]之間,便返回指向IntegerCache.cache中已經存在的物件的引用;否則建立一個新的Integer物件。

上面的程式碼中i1和i2的數值為100,因此會直接從cache中取已經存在的物件,所以i1和i2指向的是同一個物件,而i3和i4則是分別指向不同的物件。

這樣我們就不難理解為什麼一個是false,一個是true了。

其他的包裝器的valueOf方法也有不同的實現和不同的範圍,具體的我們會在原始碼深度解析專欄來分析,敬請期待~

以上就是詳解Java 自動裝箱與自動拆箱的詳細內容,更多關於Java 自動裝箱與自動拆箱的資料請關注我們其它相關文章!