Java包裝類(lèi)--自動(dòng)拆箱裝箱

1、 什么是包裝類(lèi)

包裝類(lèi)就是Java基本數(shù)據(jù)類(lèi)型的對(duì)象表示形式。其中包括基本數(shù)據(jù)類(lèi)型byte, char, short, int, long, float, double, boolean。

2、有哪些包裝類(lèi)
  • byte <====> java.lang.Byte
  • char <====> java.lang.Character
  • short <====> java.lang.Short
  • int <====> java.lang.Integer
  • long <====> java.lang.Long
  • float <====> java.lang.Float
  • double <====> java.lang.Double
  • boolean <====> java.lang.Boolean
3、為什么要用包裝類(lèi)
  1. Java是一門(mén)面向?qū)ο笳Z(yǔ)言,在進(jìn)行面向?qū)ο箝_(kāi)發(fā)時(shí),有些方法聲明必須傳入對(duì)象,而基本類(lèi)型值不具備對(duì)象特性,為了基本類(lèi)型具有對(duì)象特征,這時(shí)就出現(xiàn)了包裝類(lèi)
  2. 泛型不能使用基本類(lèi)型,例如List<T>, Set<T>, Map<K, V>
4、使用包裝類(lèi)有哪些值得注意的地方
  • byte <====> java.lang.Byte

    private static class ByteCache {
        private ByteCache(){}
    
        // byte 占一個(gè)字節(jié)8bit,有符號(hào),取值范圍 -2^7 ~ 2^7-1
        static final Byte cache[] = new Byte[-(-128) + 127 + 1];
    
        static {
            // 初始化Byte緩存
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }
    
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    

    無(wú)論short取何值, 都從緩存中的獲取。即

    Byte a = 1;
    Byte b = 1;
    System.out.println(a == b);
    // print true
    
  • char <====> java.lang.Character

    private static class CharacterCache {
        private CharacterCache(){}
    
        static final Character cache[] = new Character[127 + 1];
    
        static {
            // 緩存標(biāo)準(zhǔn)ASCII表
            for (int i = 0; i < cache.length; i++)
                cache[i] = new Character((char)i);
        }
    }
    
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }
    

    當(dāng)char取值在0~127范圍內(nèi),取緩存中的,不在次范圍內(nèi)的在java堆中創(chuàng)建新對(duì)象。即

    Character a = 'a';
    Character b = 'a';
    System.out.println(a == b);
    // print trueni
    
    Character c = '你';
    Character d = '你';
    System.out.println(c == d);
    // print false
    
  • short <====> java.lang.Short

    private static class ShortCache {
        private ShortCache(){}
    
        static final Short cache[] = new Short[-(-128) + 127 + 1];
    
        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Short((short)(i - 128));
        }
    }
    
    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);
    }
    

    當(dāng)short取值在-128~127范圍內(nèi),取緩存中的,不在次范圍內(nèi)的在java堆中創(chuàng)建新對(duì)象。即

    Short a = 1;
    Short b = 1;
    System.out.println(a == b);
    // print true
    
    Short c = 256;
    Short d = 256;
    System.out.println(c == d);
    // print false
    
  • int <====> java.lang.Integer

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

    默認(rèn),當(dāng)integer取值-128~127范圍內(nèi)時(shí),去緩存中的,不在此范圍內(nèi)的在java堆中創(chuàng)建新對(duì)象。
    Integer最大范圍可以通過(guò)設(shè)置參數(shù)java.lang.Integer.IntegerCache.high改變

    Integer a = 1;
    Integer b = 1;
    System.out.println(a == b);
    // print true
    
    Integer c = 256;
    Integer d = 256;
    System.out.println(c == d);
    // print false
    java -Djava.lang.Integer.IntegerCache.high=256
    // print true
    
  • long <====> java.lang.Long

    private static class LongCache {
        private LongCache(){}
    
        static final Long cache[] = new Long[-(-128) + 127 + 1];
    
        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 1shi28);
        }
    }
    
    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);
    }
    

    默認(rèn),當(dāng)integer取值-128~127范圍內(nèi)時(shí),去緩存中的,不在此范圍內(nèi)的在java堆中創(chuàng)建新對(duì)象。

    Long a = 1L;
    Long b = 1L;
    System.out.println(a == b);
    // print true
    
    Long c = 256L;
    Long d = 256L;
    System.out.println(c == d);
    // print false
    
  • float <====> java.lang.Float

    public static Float valueOf(float f) {
        return new Float(f);
    }
    

    無(wú)論float什么取值都從java堆中新建對(duì)象,即

    shiFloat a = 1.0f;
    Float b = 1.0f;
    System.out.println(a == b);
    // print false
    
  • double <====> java.lang.Double

    public static Double valueOf(double d) {
        return new Double(d);
    }
    

    無(wú)論double什么取值都從java堆中新建對(duì)象,即

    Double a = 1.0;
    Double b = 1.0;
    System.out.println(a == b);
    // print false
    

    為什么float和double都不緩存值?---->因?yàn)閒loat,dobule都是精度值,區(qū)間內(nèi)存在無(wú)限可取值,緩存無(wú)意義

  • boolean <====> java.lang.Boolean

    Integer a = Integer.valueOf(1);public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }
    

    boolean 只有兩種取值選擇,即true or false; 則他們?nèi)≈悼偸窍嗟取?/p>

    當(dāng)對(duì)象直接通過(guò)new創(chuàng)建,將不會(huì)發(fā)生裝箱,直接在java堆中創(chuàng)建。

5、什么情況發(fā)生自動(dòng)拆箱裝箱
  1. 賦值

    Integer a = 1;
    int b = a;
    
    //編譯后按照以下執(zhí)行
    Integer a = Integer.valueOf(1);
    int b = a.intValue();
    
  2. 運(yùn)算

    Integer a = 1;
    Integer b = 1;
    Integer c = a+b;
    
    //編譯后按照以下執(zhí)行
    Integer a = Integer.valueOf(1);
    Integer b = Integer.valueOf(1);
    Integer c = Integer.valueOf(a.intValue() + b.intValue());
    
  3. 比較

    Integer a = 1;
    int b = 2;
    System.out.println(a == b);
    
    //編譯后按照以下執(zhí)行
    Integer a = Integer.valueOf(1);
    int b = 2;
    System.out.println(a.intValue() == b);
    

    注意同是Integer類(lèi)型之間的比較不會(huì)拆箱

  4. 方法調(diào)用

    Integer a = 1;
    System.out.println(a.compareTo(2));
    
    //編譯后按照以下執(zhí)行
    Integer a = Integer.valueOf(1);
    System.out.println(a.compareTo(Integer.valueOf(2)));
    
6、包裝類(lèi)繼承結(jié)構(gòu)
以上如有錯(cuò)誤和不足的地方,請(qǐng)諒解和批評(píng)指正,不勝感激!
請(qǐng)尊重作者成果,轉(zhuǎn)載時(shí)請(qǐng)標(biāo)注原文: http://m.itdecent.cn/p/bbfc9675d63d
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 廢話不多說(shuō),自己進(jìn)入今天的主題 1、面向?qū)ο蟮奶卣饔心男┓矫妫?答:面向?qū)ο蟮奶卣髦饕幸韵聨讉€(gè)方面: - 抽象:...
    傳奇內(nèi)服號(hào)閱讀 2,538評(píng)論 1 31
  • 包裝類(lèi) 其中,前 6 個(gè)類(lèi)派生于公共的超類(lèi) Number。對(duì)象包裝器類(lèi)是不可變的,即一旦構(gòu)造了包裝器,就不允許更改...
    杰哥長(zhǎng)得帥閱讀 454評(píng)論 0 1
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,855評(píng)論 18 399
  • 當(dāng)我迷茫想去找工作的時(shí)候。東城電子的人事打我電話,我通過(guò)了鄭總工的面視,對(duì)我非常滿意,談下給我高薪。下午以為就這樣...
    鄭向飛的空間閱讀 248評(píng)論 0 0
  • 一個(gè)人吃飯 一個(gè)人上下班 一個(gè)人開(kāi)車(chē) 一個(gè)人聽(tīng)音樂(lè) 一個(gè)人健身 一個(gè)人看電影 一個(gè)人大笑 一個(gè)人哭泣 一個(gè)人清掃房...
    愛(ài)在盛夏閱讀 159評(píng)論 0 0

友情鏈接更多精彩內(nèi)容