JAVA自动装箱与拆箱

JAVA中的自动装箱与拆箱,以下面两段代码说明。

Integer i = 10;    //自动装箱

int n = i;    //自动拆箱

JDK 5 之前不存在,自动装箱。就是不能自动获取数据类型,要如下定义类型:

Integer  i  =  new  Integer(10);   //等价于 Integer i = 10; 

在面试过程中一般会有如下面试题目:

如下,判断输出结果:

public class Main {

    public static void main(String[] args) {

        

        Integer i1 = 100;

        Integer i2 = 100;

        Integer i3 = 200;

        Integer i4 = 200;
        
        System.out.println(i1==i2);    //true

        System.out.println(i3==i4);   //false

    }

}

public class Main {

    public static void main(String[] args) {


        Double i1 = 100.0;

        Double i2 = 100.0;

        Double i3 = 200.0;

        Double i4 = 200.0;


        System.out.println(i1==i2);   //false

        System.out.println(i3==i4);  //false

    }

}


public class Main {

    public static void main(String[] args) {
     

        Boolean i1 = false;

        Boolean i2 = false;

        Boolean i3 = true;

        Boolean i4 = true;
  

        System.out.println(i1==i2);    //true

        System.out.println(i3==i4);   //true

    }

}

在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。

注意,Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。

Double、Float的valueOf方法的实现是类似的。

public class Main {

    public static void main(String[] args) {

        

        Integer a = 1;

        Integer b = 2;

        Integer c = 3;

        Integer d = 3;

        Integer e = 321;

        Integer f = 321;

        Long g = 3L;

        Long h = 2L;


        System.out.println(c==d);    //true

        System.out.println(e==f);   //false

        System.out.println(c==(a+b));   //true

        System.out.println(c.equals(a+b)); //true

        System.out.println(g==(a+b)); //true

        System.out.println(g.equals(a+b)); //false

        System.out.println(g.equals(a+h)); //true

    }

}

这里面需要注意的是:当 "=="运算符的两个操作数都是 包装器类型的引用,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程)。另外,对于包装器类型,equals方法并不会进行类型转换。

猜你喜欢

转载自blog.csdn.net/yyc674002796/article/details/81536743