【JAVA】一文带你了解包装类


我们知道,java中的数据类型分为基本数据类型和引用数据类型。

//基本数据类型
int a =10;
//引用数据类型
Student s1 =new Student();

此时有一个包装类可以把基本数据类型的东西放到引用数据类型中

    int a = 10;
    Integer b = new Integer(a);

包装类的作用

  1. 可以赋值 null,解决「空值」需求
    int 默认值:0,没法区分「没赋值」和「数值就是 0」
    Integer 默认值:null
    举例:学生考试缺考,分数填 null;
    用 int 只能写 0,分不清是考 0 分还是没来考。
  2. 提供大量工具静态方法
    包装类自带一堆实用功能,基本类型做不到:
    字符串转数字:Integer.parseInt()
    数字转字符串、进制转换、最大值 / 最小值、类型判断
    各种数据格式转换

几大包装类

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

包装类赋值方法

public class test {
    public static void main(String[] args) {
        //1.直接new对象
        Integer b = new Integer(10);
        // 也可以传字符串
        Integer b2 = new Integer("10");
        System.out.println(b==b2);

        //2.静态方法赋值
        Integer c = Integer.valueOf(127);
        Integer c2 = Integer.valueOf("127");
        System.out.println(c==c2);

        //3.直接赋值(最常用)
        Integer d = 128;
        Integer d2 = 128;
        System.out.println(d==d2);
    }
}

运行结果如下

false
true
false

我们来一个个拆解

在Integer类中有一个规则,如果你写入的值在-128~127之间,他们会共用地址,因为jvm已经提前为他们创建好对象了。而在这个范围之外的就需要重新创建对象。所以在对比的时候会显示false。

那第一种赋值都是10,为什么会是false呢。其实是因为第一种直接就new了对象出来,他们的内存是不相同的。

第二第三种的底层逻辑是一样的,其实第三种是第二种的简写版,底层jvm已经替我们运行了,他们都遵循我上面说的规则。

自动装箱和自动拆箱

箱子:其实就是对象,引用数据类型。

自动拆箱:我们都知道对象是不能直接进行加减的,而在包装类中,一旦使用他们的对象进行加减,就会触发自动装箱,也就是把他们的类型自动转化为基本数据类型。

自动装箱:当加减完后,数值要传递给包装类的对象时,会触发自动拆箱,也就是把基本数据类型再转化为引用数据类型,然后再赋值。

public class test {
    public static void main(String[] args) {
        // 【自动装箱】int基本值 → Integer包装对象
        // 底层:Integer x = Integer.valueOf(100);
        Integer x = 100;

        // 【自动拆箱】Integer包装对象 → int基本类型
        // 底层:int y = x.intValue();
        int y = x;

        // 【自动装箱】底层:Integer m = Integer.valueOf(200);
        Integer m = 200;

        // 运算触发自动拆箱
        // 底层:int res = m.intValue() + 10;
        int res = m + 10;
        
        System.out.println(res);
        //结果为210
    }
}

包装类里的equals

public class test {
    public static void main(String[] args) {
        //1.直接new对象
        Integer b = new Integer(10);
        // 也可以传字符串
        Integer b2 = new Integer("10");
        System.out.println(b.equals(b2));
        //结果为true
    }
}

在包装类里面,equals的方法已经被重写过了,所以即使用超过范围的或者用new关键字的对象进行对比的时候,都对比的是数值而不是地址。

总结

本文一共介绍了什么是包装类,包装类的作用,使用方法以及一些底层细节。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐