一、什么是装箱拆箱?
java为每种基本数据类型提供了对应的包装器类型
Integer i = 10;
拿烟的手微微颤抖:这样就生成了一个特数值为10的Integer对象,这个过程中会自动创建对应的Integer对象。
name什么是拆箱呢?
Integer i = 10;//装箱
int n = i;//拆箱
总结:
装箱就是把自动基本数据类型装换为包装器类型,拆箱就是自动将包装器类型转换成基本数据类型。
下面是基本类型对应的包装器类型:
int(4字节) Integer
byte(1字节) Byte
short(2字节) Short
long(8字节) Long
float(4字节) Float
double(8字节) Double
char(2字节) Character
boolean(未定) Boolean
二、实现原理
看段代码:
1 packagecn.zpoor.test;2 /**
3 *@author薛定谔的猫4 * 自动装箱拆箱*/
5 public classMain {6 public static voidmain(String[] args) {7 Integer i = 10;8 int n =i;9 }10 }
jd反编译之后:
不要慌,冷静分析:在装箱的时候自动调用的是Integer的valueOf()方法,拆箱的时候是自动调用Integer的intValue()方法。
总结:装箱过程是通过调用包装器的valueOf方法实现,拆箱过程是通过调用包装器的xxxValue方法实现的(xxx代表基本数据类型)
三、装箱和拆箱的面试问题
1、这段代码输出的是什么?
1 packagecn.zpoor.test;2 /**
3 *@author薛定谔的猫4 * 自动装箱拆箱*/
5 public classMain {6 public static voidmain(String[] args) {7 Integer i1 = 100;8 Integer i2 = 100;9 Integer i3 = 200;10 Integer i4 = 200;11
12 System.out.println(i1 ==i2);13 System.out.println(i3 ==i4);14 }15 }16
17
18 /*结果:19 * true20 false21 */
为什么呢?
看一段源码:
1 public static Integer valueOf(inti) {2 if (i >= IntegerCache.low && i <=IntegerCache.high)3 return IntegerCache.cache[i + (-IntegerCache.low)];4 return newInteger(i);5 }
在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象,否则创建一个新的对象。
所以i1和i2是一个对象,i3和i4则指向不同的对象。
2、这段代码输出什么?
1 packagecn.zpoor.test;2 /**
3 *@author薛定谔的猫4 * 自动装箱拆箱*/
5 public classMain {6 public static voidmain(String[] args) {7 Double i1 = 100.0;8 Double i2 = 100.0;9 Double i3 = 200.0;10 Double i4 = 200.0;11 System.out.println(i1 ==i2);12 System.out.println(i3 ==i4);13 }14 }15
16
17 /*结果:18 * false19 false20 */
为啥呢?
因为Double包装器的valueOf方法返回的是一个新的对象,所以每个对象都不一样。还是一句话,多看看源码。
3、这段代码输出什么?
1 packagecn.zpoor.test;2 /**
3 *@author薛定谔的猫4 * 自动装箱拆箱*/
5 public classMain {6 public static voidmain(String[] args) {7 Boolean i1 = false;8 Boolean i2 = false;9 Boolean i3 = true;10 Boolean i4 = true;11 System.out.println(i1 ==i2);12 System.out.println(i3 ==i4);13 }14 }15
16
17 /*结果:18 * true19 * true20 */
冷静分析:
看源码
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
我这样说,你大概懂了吧。
4、谈谈Integer i = new Integer(xxx) 和 Integer i = xxx; 这两种方式的区别?
一:第一种方式不会触发自动装箱的过程;第二种方式会触发。
二:在执行效率和资源占用的区别。第二种方式的执行效率和资源占用在一般性情况下优于第一种情况(但不是绝对的)
分析完毕之后:拿烟的手,微微颤抖。