【Java學習筆記】自動封包和解包(Autoboxing和AutoUnboxing)


作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/

import java.util.ArrayList;

public class Autoboxing {
    public static void main(String[] args) {
//        手動打包,解決容器類無法放置基本數據類型的問題
        Integer intvalue = new Integer(1);//封裝類為引用類型,棧中保存的是引用,堆上存放實際值
        Double doublevalue = new Double(0.5);
        Float floatvalue = new Float(1.1f);
        
        int intVar = intvalue.intValue();//基本數據類型是直接存放在棧上的
        double doubleVar = doublevalue.doubleValue();
        Float floatVar = floatvalue.floatValue();
        
        System.out.println(intVar +" " + doubleVar +" " +floatVar);
        
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(intvalue);
        arr.add(1);//自動封包,將基本數據類型轉為包裝類。
        
       int a = arr.get(0);//自動解包
       
       Integer i = 2;//自動封包
       
       int b = i+2;//自動解包
       Integer c=b+2;//自動封包
       
       System.out.println(b);            
    }
}
 
我注意到在specification中有這么一句,
If the value p being boxed is true, false, a byte, a char in the range /u0000 to
/u007f, or an int or short number between -128 and 127, then let r1 and r2 be
the results of any two boxing conversions of p. It is always the case that r1 ==
r2.
也就是說這樣的兩個值在自動封包后r1==r2總返回是ture。

 

作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM