从基本数据类型到包装类型的过程是装箱、从包装类型到基本数据类型的过程是拆箱。
例子:
Integer包装类 ——int基本数据类型
public static void main(String []args){
Integer a=1000;
Integer b=1000;
Integer c=10;
Integer d=10;
System.out.println(a==b);
System.out.println(c==d);
}
输出:
false
true
Integer a=1000; //称为隐式加包
实际上是通过这实现的: Integer a=Integer.valueof(1000);//显式加包
对于-128到127之间的数,会进行缓存,已经在堆里面有缓存。下次再写Integer j = 127时,就会直接从缓存中取,就不会new了。
除非 integer a=new(127);不会用缓存里面的。
***显示、隐式加包、拆包
public static void main(String []args){
Integer a=1000; //隐式加包
Integer b1=Integer.valueOf(1000); //显式加包
int d=a; //隐式拆包 (调用intvalue)
int e=a.intValue(); //显式拆包
System.out.println(a);
System.out.println(b1);
System.out.println(d);
System.out.println(e);
}
除了Integer
其他的包装类型:
Boolean: (全部缓存)
Byte: (全部缓存)
Character ( <=127 缓存)
Short (-128~127 缓存)
Long (-128~127 缓存)
Float (没有缓存)
Doulbe (没有缓存)
二者之间也存在一些区别:
1.声明方式不同,基本类型不适用new关键字,而包装类型需要使用new关键字来在堆中分配存储空间;
2.存储方式及位置不同,基本类型是直接将变量值存储在堆栈中,而包装类型是将对象放在堆中,然后通过引用来使用;
3.初始值不同,基本类型的初始值如int为0,boolean为false,而包装类型的初始值为null
4.使用方式不同,基本类型直接赋值直接使用就好,而包装类型在集合如Collection、Map时会使用到。