java自動裝箱與拆箱

首先我們來解釋下什么叫做自動裝箱與拆箱:
自動裝箱就是Java自動將原始類型值轉換成對應的對象,反之將對象轉換成原始類型值,這個過程叫做拆箱。

原始類型與封裝類

原始類型 byte short char int long float double boolean
對應封裝類 Byte Short Character Integer Long Float Double Boolean

過程

自動裝箱時編譯器調用valueOf將原始類型值轉換成對象
同時自動拆箱時,編譯器通過調用類似intValue(),doubleValue()這類的方法將對象轉換成原始類型值。

裝箱過程是通過調用包裝器的valueOf方法實現的,而拆箱過程是通過調用包裝器的 xxxValue方法實現的,算數表達式會自動引發拆箱。

源碼

int類型自動裝箱:(如Integer i = 10;)

public static Integer valueOf(int i) {
  //判斷i是否在-128和127之間,如果不在此范圍,則從IntegerCache中獲取包裝類的實例。否則new一個新實例
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}
 
 
//使用亨元模式,來減少對象的創建
private static class IntegerCache {
  static final int low = -128;
  static final int high;
  static final Integer cache[];
 
  //靜態方法,類加載的時候進行初始化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() {}
}

可以看出以上代碼說明自動裝箱的時候,通過valueOf方法創建Integer對象,如果數值在[-128,127]之間,便返回指向IntegerCache.cache中已經存在的對象的引用,否則創建一個新的Integer對象,這樣可以保證經常用到的integer對象不用一再創建。

8大基本類型的裝箱源碼:

//boolean原生類型自動裝箱成Boolean
public static Boolean valueOf(boolean b) {
  return (b ? TRUE : FALSE);
}
 
//byte原生類型自動裝箱成Byte
public static Byte valueOf(byte b) {
  final int offset = 128;
  return ByteCache.cache[(int)b + offset];
}
 
//short原生類型自動裝箱成Short
public static Short valueOf(short s) {
  final int offset = 128;
  int sAsInt = s;
  if (sAsInt >= -128 && sAsInt <= 127) { // must cache
    return ShortCache.cache[sAsInt + offset];
  }
  return new Short(s);
}
 
//char原生類型自動裝箱成Character
public static Character valueOf(char c) {
  if (c <= 127) { // must cache
    return CharacterCache.cache[(int)c];
  }
  return new Character(c);
}
 
//int原生類型自動裝箱成Integer
public static Integer valueOf(int i) {
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}
 
//int原生類型自動裝箱成Long
public static Long valueOf(long l) {
  final int offset = 128;
  if (l >= -128 && l <= 127) { // will cache
    return LongCache.cache[(int)l + offset];
  }
  return new Long(l);
}
 
//double原生類型自動裝箱成Double
public static Double valueOf(double d) {
  return new Double(d);
}
 
//float原生類型自動裝箱成Float
public static Float valueOf(float f) {
  return new Float(f);
}

可以看出,除了double和float的自動裝箱代碼沒有使用緩存,每次都是new 新的對象外,其它的6種基本類型都使用了緩存策略。

其中Boolean中定義了2個靜態成員屬性:

public static final Boolean TRUE = new Boolean(true);
/** 
* The <code>Boolean</code> object corresponding to the primitive 
* value <code>false</code>. 
*/
public static final Boolean FALSE = new Boolean(false);

Integer i = new Integer(xxx)和Integer i =xxx;的區別。

1)第一種方式不會觸發自動裝箱的過程;而第二種方式會觸發;

2)在執行效率和資源占用上的區別。第二種方式的執行效率和資源占用在一般性情況下要優于第一種情況(這并不是絕對的)。

下面程序的輸出結果是什么?

public class Main {
  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);
    System.out.println(e==f);
    System.out.println(c==(a+b));
    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));
  }
}

輸出結果:

true
false
true
true
true
false
true

當 “==”運算符的兩個操作數都是包裝器類型的引用(integer在數值在-127~128之間會返回緩存的對象),則是比較指向的是否是同一個對象,而如果其中有一個操作數是表達式(包含算術運算)則比較的是數值(會觸發自動拆箱的過程)。

對于包裝器類型,equals方法并不會進行類型轉換。

第一個和第二個輸出結果沒有什么疑問。
第三句由于 a+b包含了算術運算,因此會觸發自動拆箱過程(會調用intValue方法),因此它們比較的是數值是否相等。
而對于c.equals(a+b)會先觸發自動拆箱過程,再觸發自動裝箱過程,也就是說a+b,會先各自調用intValue方法,得到了加法運算后的數值之后,便調Integer.valueOf方法,再進行equals比較。
同理對于后面的也是這樣,不過要注意倒數第二個和最后一個輸出的結果(如果數值是int類型的,裝箱過程調用的是Integer.valueOf;如果是long類型的,裝箱調用的Long.valueOf方法)。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容