天天看點

Java 自動拆箱裝箱原理

1.需要自動拆箱裝箱的類型

Java 自動拆箱裝箱原理

2. 基本類型及其包裝類型

Java 自動拆箱裝箱原理

3.什麼是自動拆箱裝箱

裝箱,就是将基本資料類型轉換成包裝器類型。

拆箱,就是自動将包裝類型轉換成基本資料類型

//自動裝箱
Integer total = 99;
//自動拆箱
int totalprim = total;
           

看個栗子

public class StringTest {
    public static void main(String[] args) {
        //自動裝箱
        Integer total = 99;
        //自定拆箱
        int totalprim = total;
    }
}
           

編譯Java源碼

javac StringTest.java
javap -c StringTest.class
           

javap 檢視彙編指令結果

D:\ideaworkspace\test\src\testtool>javap -c StringTest.class
Compiled from "StringTest.java"
public class testtool.StringTest {
  public testtool.StringTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: bipush        99
       2: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #3                  // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: return
}
           

自動裝箱

執行 Integer total =99;

執行代碼時系統為我們執行了 Integer total = Integer.valueOf(99);

這個就是自動裝箱。

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * 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
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
           

自動拆箱

執行 int totalprism  =  total 時 系統自動執行了

int totalprim = total.intValue();

/**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
 public int intValue() {
        return value;
 }