【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