Java知识点梳理——装箱和拆箱

1、前言:Java是典型的面向对象编程语言,但其中有8种基本数据类型不支持面向对象编程,基本数据类型不具备对象的特性,没有属性和方法;Java为此8种基本数据类型设计了对应的类(包装类),使之相互转换,间接实现基本数据类型具备对象特性,丰富基本数据类型操作;

基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean  

  

注:int是基本数量类型,Integer是类;int和Ingeger初始值不同(int默认值0 Ingeger默认值null);Integer包含属性和方法,int则没有;基本数据类型和包装类相互转换的过程叫装箱和拆箱;

2、装箱:基本数据类型转换成对应的包装类(int——>Integer);

Integer i = new Integer(10); // 手动装箱
 Integer i = 10; // 自动装箱

3、拆箱:包装类转换成基本数据类型(Integer——>int);

Integer i = Integer.valueOf(10); // 调用valueOf方法自动装箱
 int n = i.intValue(); // 调用intValue方法自动拆箱
 

注:自动装箱会隐式地创建对象,在一个循环中注意自动装箱问题,影响程序性能;

5、equals 和 == 比较:当 "=="运算符的两个操作数都是包装类,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(触发自动拆箱);对于包装类,equals方法不会进行类型转换;

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
    }
}

解析:JVM会缓存-128到127的Integer对象(Short、Byte、Character、Long与Integer类似),所以第一个是同一个对象true,第二个是new的新对象false;第三个有+法运算比较的是两边的值true;第四个有+法运算且两边的数据类型相同true;第五个同四先求+法求和 ,==会进行类型转换(Long)true;第六个先+法求和,equals不会类型转换false;第七个先+法求和(触发拆箱,变成了int类型和long类型相加,这个会触发类型晋升,结果是long类型的)equals比较时触发装箱比较两边都是Long类型结果true;

猜你喜欢

转载自www.cnblogs.com/songanwei/p/9390559.html