Java 拆箱與裝箱

在Java中每個基本數據類型都有對應的一個類,

基本類型 對應的類
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
void Void
boolean Boolean
 - 這些對象包裝器是不可變的,也就是說一旦生成了一個對應的對象之後裏面的值就不能改變了。 並且它們還是final的,所以不能定義它們的子類。
 - 當我們在構造列表`(例如ArraList<Integer>)`的時候,`<>`之間只能傳遞對象,這個時候我們就可以傳遞它們對應的類。

一、裝箱

  • 既然這些類都是箱子,那麼把基本類型變成這些類的對象就是 裝箱 的操作了。但是裝箱的操作是由編譯器自動來完成的,跟jvm無關。所以又稱爲自動裝箱。
Integer a=10;//相當於是Integer a = Integer.valueOf(10);

二、拆箱

當我們將Integer對象賦給int時,將會自動拆箱。也就是編譯器會完成以下動作:

int b=a;   =>   int b = a.intValue();

有時的計算可以自動拆箱和裝箱,例如:

a++;

三、注意事項

/**
     * 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) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

從以上說明可以看到不是任何時候調用 valueOf(int i) 都會新實例化一個對象返回

Integer a = 90;
        Integer b = 90;
        Integer c = Integer.valueOf(90);
        Integer d = new Integer(90);
        if (a == b) {
            System.out.println("a==b");
        }
        if (c == b) {
            System.out.println("c==b");
        }
        if (c == d) {
            System.out.print("c==d");
        }else{
            out.println("c!=d");
}

----------
輸出:
a==b
c==b
c!=d。

實際上,當初始化的值 在[-128,127]這個區間的時候只會返回已經緩存的對象,所以這個時候都是一樣的,只有當初始的值不在這個範圍的時候纔會返回一個新new的對象,這個時候他們就不一樣了

   Integer b = -129;
   if (a == b) {
            System.out.println("a==b");
        }else{
    System.out.println("a!=b");
}

輸出:
a!=b

四、比較
當對象包裝器直接比較的時候是跟上面的所說的一樣,但是當對象包裝器和一般的基本類型比較的時候就是先拆箱然後比較兩者直接的“內容(這裏就是數值)”,所以當一個對象包裝器和一時候,如果兩者的值一樣那麼它們就是一樣的

Integer d = new Integer(90); 
       int e = 90;
        if (e == d) {
            out.println("e==d");
        }
輸出:
("e==d");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章