包装类

包装类(Wrapper Class)

什么是包装类?

以类的形式将java八大基本数据类型进行封装,以对象的方式来进行创建和使用。

为什么需要包装类?

java是一门面向对象的语言,许多方法需要以对象的形式传递或返回参数,但java提供的八大基本数据类型并不属于对象,所以为了方便使用,需要先对其进行封装成类。

基本数据类型和包装类的对应关系

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

包装类的主要作用

  • 方便涉及对象操作
  • 包装类对象包含了最大值、最小值等相关属性,方便调用
  • 包装类有相关的操作方法,方便使用
  • 特别的,包装类可以实现基本数据类型和String之间的转换
@Test
public void test() {

    List list = new ArrayList();
    list.add(80);//jdk1.5以上,自动装箱,简化包装类的使用
    list.add(new Integer(80));//手动装箱

    //包装类提供更多的功能
    System.out.println(Integer.MAX_VALUE);//2147483647,整型的最大值
    System.out.println(Integer.MIN_VALUE);//-2147483648,整型的最小值
    System.out.println(Integer.SIZE);//32,整型的位数
    System.out.println(Integer.toBinaryString(12));//1100,整数转二进制字符串
    System.out.println(Integer.toOctalString(12));//14,转八进制
    System.out.println(Integer.toHexString(12));//c,转十六进制

    //字符串和基本类型的转换
    String str = "123";
    //Int i = str;报错,String类型不能直接赋值给Int类型
    //Int i = Int(str);报错,不满足强转条件,instanceof
    int i = Integer.parseInt(str);//将字符串转成整数123,如网页传参age、score等转换成数值
    double d = Double.parseDouble("18.5");

}


包装类和基本数据类型的区别

  1. 包装类需要占用栈内存和堆内存,基本数据类型只只用栈内存
  2. 作为成员变量,默认值不同,如Integer默认为null,Int默认0
  3. 后者在使用上更灵活、简单和高效

自动装箱和自动拆箱

  • auto-boxing
  • auto-unboxing
@Test
public void test() {

    int i = 5;
    //Integer i2 = new Integer(6);//手动装箱,不必要的使用方式
    Integer i2 = 6;//自动装箱
    //i = i2.intValue();//手动拆箱,不必要的使用方式
    i = i2;//自动拆箱


}

比较

  • 六个数字的包装类都是Number的子类

@Test
public void test() {
    int i = 5;
    Integer i1 = 5;//自动装箱,未调用构造器
    Integer i2 = new Integer(5);
    Integer i3 = new Integer(5);
    Integer i4 = 5000;
    Integer i5 = 5000;//自动装箱,调用构造器
    Integer i6 = i5;
    int i7 = i;

    System.out.println(i==i1);//true,自动装箱时,如果值在-128-127直接返回value,不调用new Integer()
    System.out.println(i4==i5);//false
    System.out.println(i5==i6);//true
    System.out.println(i2==i3);//false,==比较的是引用地址值
    System.out.println(i2.equals(i3));//true,equals()比较的是堆内存里存的值

}
原文地址:https://www.cnblogs.com/zuozs/p/14514929.html