Java中特殊的类---包装类

目录

基本原理

分类

装箱与拆箱

字符串与基本数据类型转换


基本原理

包装类就是将基本数据封装到类中。

自己定义一个包装类并使用:

class IntDemo{
    private int num;
    public IntDemo(int num){
        this.num = num;
    }
    public int intvalue(){
        return this.num;
    }
}

public class Test{
    public static void main(String[] args){
     Object obj = new IntDemo(10); //向上转型
     IntDemo tmp = (IntDemo)obj; //向下转型(进行向下转型,要先向上转型)
     System.out.println(tmp.intvalue());
    }
}

分类

1.对象型包装类(Object的直接子类):Boolean,Character

2.数值型包装类(Number的直接子类):Byte,Short,Double,Long,Integer,Float

说明:

Number类的定义:public abstract class Number implements java.io.Serializable

装箱与拆箱

  • 装箱:将基本数据类型变为包装类对象,利用每一个包装类提供的构造方法实现装箱处理。
  • 拆箱:将包装类中包装的基本数据类型取出。
public class Test{
    public static void main(String[] args){
    //手动装箱与拆箱
    Integer num = new Integer(10); //装箱
    int data = num.intValue(); //拆箱
    System.out.println(data);
    //自动装箱与拆箱
    Integer i = 5; //装箱
    System.out.println(i*5);//直接利用包装类对象操作
    }
}

阿里编码规范:所有的相同类型的包装类对象之间值的比较,全部使用equals方法比较。

说明:

对于Integer var = ? 在-128~127之间的赋值,Integer对象在Integer常量池产生,会复用已有对象,这个区间内的Integer值可以直接使用==判断。除此之外的所有数据,都会在堆上产生,并不会复用已有对象

阿里编码规范:使用int还是Integer?

a. 【强制】所有的POJO类属性必须使用包装类型

b. 【强制】RPC方法的返回值和参数必须使用包装类型

c. 【推荐】所有的局部变量使用基本类型

字符串与基本数据类型转换

1. 将字符串转为基本类型(静态方法)

调用各个包装类.parsexx(String str)

public class Test{
    public static void main(String[] args){
        String str = "345";
        int num = Integer.parseInt(str);
        System.out.println(num);
    }
}

需要注意的是:将字符串转为数字的时候,如果字符串包含非数字,就会出现错误(NumberFormatException)。

2. 基本类型变为字符串

a. ""+基本类型

b. 使用String类的valueof()方法,此方法不产生垃圾空间(推荐)

public class Test{
    public static void main(String[] args){
    String str = String.valueOf(50);
    System.out.println(str);      
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_40931662/article/details/83789922