Java的自动装箱与拆箱小结

Java中,装箱就是  自动将基本数据类型转换为包装器类型;拆箱就是  自动将包装器类型转换为基本数据类型。

自动装箱与拆箱的特点有

(1)包装器类型与基本数据类型之间可以进行比较,以及运算,在过程中,需要将包装器类型拆箱,再进行比较及运算
        (2)包装器类型之间也可以进行比较及运算,也是需要先将其拆箱,再进行比较及运算。
        (3)如果值不在-128~127之间,则在装箱的时候,会创建一个新的对象,float类型及double类型则一定会创建新的对象。

(4)包装器类型的equals方法经过覆盖了object类的equals方法,查看源码可知它先判断两个对象是否是同一类型,如果不是的话,就返回false,如果是的话,再比较对象中存的值。

        int a = 1;
        Integer b = 1;
        Integer c = 1;
        Integer d = 2;
        Integer e = 3;
        Integer f = 128;
        Integer g = 128;
        Long h = 3L;
        Double m = 4.0;
        Double n = 4.0;
        Float p = 5f;
        Float q = 5f;
        System.out.println("a == b : " + (a == b));  //true
        System.out.println("b ==c : " + (b == c));  //true
        System.out.println("e == (c + d) : " + (e == (c + d)));  //true
        System.out.println("e.equals(c + d) : " + (e.equals(c + d)));  //true
        System.out.println("h == (c + d) : " + (h == (c + d))); //true
        System.out.println("h.equals(c + d) : " + (h.equals(c + d)));  //false
        System.out.println("f == g : " + (f == g)); //false
        System.out.println("m == n : " + (m == n)); //false
        System.out.println("p == q : " + (p == q)); //false
        System.out.println("m == d * 2 : " + (m == d * 2)); //true
        System.out.println("p == (d + e) : " + (p == (d + e))); //true

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章