基本概念
包装类主要功能是针对基本数据类型对象转换而实现的,随jdk版本更新改变。
Object类是所有类的父类,并且可以接受所有数据类型,但是这个过程中有个问题:基本数据类型并不是一个类。如果想要将基本数据类型以类形式进行处理,那么就要对其进行包装。
例子:以int数据为例处理包装类
class Int{
private int data; //包装了一个基本数据类型
public Int(){}
public Int(int data){
this.data=data;
}
public int print(){
return this.data;
}
}
public class Baozhuang {
public static void main(String[] args)
{
//装箱:将基本数据类型保存在包装类对象中
Object a=new Int(10);//向上转型
//拆箱:从包装类对象中获取基本数据类型
int x=((Int) a).print();//向下转型
System.out.println(x); //10
}
}
包装类的本质:
基本数据类型处理后可以像对象一样进行引用传递,同时也可以使用Object类来进行数据接收。
基本数据类型一共八种,包装类也有八种。
可以发现Java中包装类提供两种类型:
·对象型包装类(object直接子类):Boolean,Character
·数值型包装类(number直接子类):Byte ,Short, Integer,Long,Float,Double
Number是一个抽象类,定义如下方法:
装箱与拆箱
基本数据类型的包装类都是为了基本数据类型转为对象提供的。
·数据装箱:将基本数据类型保存到包装类之中,一般可以利用构造方法完成;
——Integer类:public Integer(int value);
——Double类:public Double(double value);
——Boolean类:public Boolean(boolean value);
·数据拆箱:从包装类中获取基本数据类型;
——Number已经提供拆箱方法
——Boolean型:public boolean booleanValue();
例子:以int与Integer为例
public class Baozhuang {
public static void main(String[] args)
{
//装箱:将基本数据类型保存在包装类对象中
Integer a=new Integer(10);
//拆箱:从包装类对象中获取基本数据类型
int x=a.intValue();
System.out.println(x*x); //100
}
}
例子:以double与Double为例
public class Baozhuang {
public static void main(String[] args)
{
//装箱:将基本数据类型保存在包装类对象中
Double a=new Double(10.1);
//拆箱:从包装类对象中获取基本数据类型
double x=a.doubleValue();
System.out.println(x*x); //102.00999999999999
}
}
例子:boolean与Boolean
public class Baozhuang {
public static void main(String[] args)
{
//装箱:将基本数据类型保存在包装类对象中
Boolean a=new Boolean(true);
//拆箱:从包装类对象中获取基本数据类型
boolean x=a.booleanValue();
System.out.println(x); //true
}
}
自动装箱与自动拆箱
例子:观察自动拆箱与装箱
public class Baozhuang {
public static void main(String[] args)
{
Boolean a=true;//自动装箱
boolean x=a;//自动拆箱
a++;//包装类对象可以直接参与数学运算
System.out.println(x); //true
}
}
除了提供自动的数学运算支持以为,使用自动装箱最大的好处就是可以实现Object接收基本数据类型操作。
例子:实现自动拆箱与装箱
public class Baozhuang {
public static void main(String[] args)
{
//double自动装箱为Double,向上转型为Object
Object a=19.2;
//向下转型为包装类,再自动拆箱
double x=(double) a;
System.out.println(x*10); //192.0
}
}
包装类相等判断
对于包装类需要注意关于相等判断
例子:观察相等判断
public class Baozhuang {
public static void main(String[] args)
{
Integer x=199;
Integer y=199;
System.out.println(x==y); //false
System.out.println(x.equals(y)); //true
}
}
·当用==时,如果x值大于127或小于(-128),结果为false;
·当用equals时,不受影响。
进行包装类进行相等判断,选择equals判断。
综合应用
public class Baozhuang {
public static void main(String args[]) {
//手动装箱,拆箱
Integer a=new Integer(10);
int x=a.intValue();
System.out.println(x);
//自动装箱与拆箱
Integer b=10;
int y=10;
System.out.println(y);
//向上向下转型与装箱拆箱
Object c=10;
int z=(int) a;
System.out.println(z);
}
}