java 自動裝箱、拆箱

來源:互聯網
上載者:User

標籤:ash   設定   stat   三目運算   html   out   integer   資料類型   final   

# java 自動裝箱、拆箱

從 jdk 1.5 版本開始, 引入該功能。

一、自動裝箱

將基礎資料型別 (Elementary Data Type)自動封裝為對應封裝類。

程式碼範例,

Integer i = 100;

100屬於基本類型int,會自動裝箱,如下:

Integer i = Integer.valueOf(100);

相當於,

Integer i = new Integer(100);
二、自動拆箱

將封裝類自動轉換為對應的基礎資料型別 (Elementary Data Type)。

程式碼範例,

Integer i = new Integer(100);int j = i;

i屬於封裝類Integer,會自動拆箱,如下:

Integer i = new Integer(100);int j = i.intValue();
三、問題
  • 三目運算子

問題代碼(會引起NPE問題),

Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : false);

問題原因:三目運算子第二、三運算元類型不同(一個為對象,一個為基礎資料型別 (Elementary Data Type)),會將對象自動拆箱為基礎資料型別 (Elementary Data Type)。

拆箱過程,

Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = Boolean.valueOf(map != null ? map.get("test").booleanValue() : false);

問題解決,

Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : Boolean.FALSE);
  • Integer

相關代碼,

Integer int1 = 100;Integer int2 = 100;Integer int3 = 300;Integer int4 = 300;    // trueSystem.out.println(int1 == int2);// falseSystem.out.println(int3 == int4);

引起問題原因:裝箱調用了Integer.valueOf()。源碼如下,

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);}

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) {            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);        }        high = h;        cache = new Integer[(high - low) + 1];        int j = low;        for(int k = 0; k < cache.length; k++)            cache[k] = new Integer(j++);    }    private IntegerCache() {}}

未進行特別設定,IntegerCache.high取值為127。因此,通過Integer.valueOf()方法建立Integer對象的時候,如果數值在[-128,127]之間,返回IntegerCache.cache中對象的引用,否則建立一個新的Integer對象。

java 自動裝箱、拆箱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.