Java_64_自动装箱和拆箱(autoboxing,unboxing)_

自动装箱和拆箱(autoboxiong,unboxing)

就是将基本类型和包装类型进行自动的互相转换。

JDK5.0后,将自动装箱/拆箱引入Java中。

自动装箱的过程:每当需要一个类型的对象时,这种基本类型就自动的封装到与它相同类型的包装中。

自动拆箱的过程:每当需要一个值时,被装箱对象中的值就被自动的提取出来,没必要再去调用intValue()和doubleValue()方法。

自动装箱与拆箱的功能事实上是编译器来帮助你的忙,编译器在编译时期依你所编写的语法,决定是否进行装箱或拆箱动作。

例如:Integer i=100;

相当于编译器自动为你做以下的语法编译:

Integer i=new Integer(100);

所以自动装箱与拆箱的功能是所谓的“编译器蜜糖”(Compiler Sugar),虽然使用这个功能很方便,但在程序运行阶段你得了解Java的语义。例如下面的程序是可以通过编译的:

Integer i=null;

int j=i;

这样的语法在编译时期是合法的,但是在运行时期会有错误,因为这种写法相当于:

Integer i=null;

int j=i.intValue();

null表示i没有参考至任何的对象实体,它可以合法的指定给对象参考名称。由于实际上i并没有任何参考至任何的对象,所以也就不可能操作intValue()方法,这样上面的写法在运行时会出现NullPointerException错误。

/**

*测试自动装箱和拆箱

*结论:虽然很方便,但是如果不熟悉特殊情况,可能会出错。

*/

static void testBoxing(){

Integer b=23; //自动装箱

int a=new Integer(20); //自动拆箱

//自动装箱和拆箱,实际上是编译器替我们完成了代码的自动编译

//比如:Integer b=23

//其实运行时执行的仍然是:Integer b=new Integer(23);

//下面的问题我们需要注意:

//Integer c=null;

//int d=c; //此处其实就是:c.intValue(),因此抛出空指针异常。

//自动装箱拆箱时,Integer 范围:对于-128到+127之间的值,编译器仍然会把他们当做基本类型处理。

Integer h=100;Integer u=100;

Integer h2=200;Integer u2=200;

if(h==u){

System.out.println("100等于");

}

if(h2==u2){

System.out.println("200等于");

}

}

public static void main(String[] args) {
        Integer a=0;
        int a1=a;
        System.out.println(a1);
        
        Integer a2=1234;
        Integer a3=1234;
        System.out.println(a2==a3);          //false
        System.out.println(a2.equals(a3));  //true
        /**
         * Integer范围在-128到+127
         */
        Integer a4,a5;
        a4=-128;
        a5=-128;
        System.out.println(a4==a5);          //true
        System.out.println(a4.equals(a5));  //true
    }

发布了136 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/pmcasp/article/details/84555415