装箱:将基本类型转换为包装类。
integer i1 = 10;//自动装箱
valueOf()方法,装箱
显式装箱
Integer i2 = (Integer)10;//显式装箱
Integer i3 = new Integer(10);
i3放在栈上, new Integer(10)放在堆上。i3存储的是new Integer(10)的地址。
在-128 - 127范围内,将数据放入缓存中,不再这个范围内,new 一个新的对象。
valueof()方法
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer i4 = 128;
Integer i5= 128;
System.out.println(i4==i5);//false
System.out.println(i4.equals(i5));//true
拆箱:将包装类转换成基本类型。一般来说调用intValue()、doubleValue()方法等。
int ii1 = i1; //拆箱
总结:
自动装箱时编译器调用valueOf将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。自动装箱是将boolean值转换成Boolean对象,byte值转换成Byte对象,char转换成Character对象,float值转换成Float对象,int转换成Integer,long转换成Long,short转换成Short,自动拆箱则是相反的操作。