自动拆装箱
自动装箱:
基本类型的数据处于需要对象的环境中时会自动转为对象。
以Integer为例:在JDK1.5之前,Integer i=5 是错误的,必须要通过 new 来实现基本数据类型转换成包装类的过程;在1.5之后 Java提供了自动装箱的功能,因此只需要Integer i=5 这样就可以实现基本类型转换成包装类,这是因为JVM为我们执行了Integer i=Integer.valueOf(5) 这样的操作,这就是java的自动装箱。
自动拆箱:
每当显示一个值的时候,对象会自动转成基本类型的数据,没必要显式调用intValue(),doubleValue() 等转型方法。
如Integer i=5; int j=i;这样的过程就是自动拆箱。
总结:
自动装箱的过程是通过调用包装类的valueOf实现的,自动拆箱是通过调用包装类的xxxValue()方法实现的xxx指的是对应的基本类型如intValue()
package cn.dct.oop;
public class TestAutoBox {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=234; //自动装箱Integer a=Integer.valueOf(234);
int b=a; //自动拆箱int b=a.intValue();
Integer c=null;
//int d=c; //报空指针异常 调用了c.intValue(); 需要加非空判断
if(c != null) { int d=c;}
//缓存[-128,127]之间的数字,系统初始的时候,创建了[-128,127]之间的缓存数组
//当我们调用valueOf()的时候会首先检查是否在数组里,如果在这个范围就直接从缓存数组中拿出已建好的对象
//不在则创建新的Integer对象
Integer int1=Integer.valueOf(-128);
Integer int2=-128;
System.out.println(int1==int2);//因为-128在缓存范围内
System.out.println(int1.equals(int2));
System.out.println("===========================");
Integer int3=Integer.valueOf(1234);
Integer int4=1234;
System.out.println(int3==int4);//1234不在缓存范围内
System.out.println(int3.equals(int4));
System.out.println("===========================");
}
}
================结果
true
true
false
true
================================
加群获取学习资源,一起学习