示例代码
public static void main(String[] args) {
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a == b;//自动拆箱,xxxValue()
boolean equal2 = a.equals(b);//自动装箱, valueOf()
System.out.println(equal1);
System.out.println(equal2);
}
反编译后
public static void main(String args[])
{
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a.intValue() == b; //自动拆箱
boolean equal2 = a.equals(Integer.valueOf(b));//自动装箱
System.out.println(equal1);
System.out.println(equal2);
}
区别
- Integer 是引用类型,int是基本类型
- Ingeter是int的包装类,内部封装持有一个int类型的值。int的初值为0,Ingeter的初值为null。
- Integer是引用类型,Integer间的比较必须用 equals()
拆箱
当 Integer a 与 int b 进行运算时,如:比较、加减等,会自动拆箱,即获取a持有的 int 值,然后再与 b 进行运算。
包装类型的拆箱通过 xxxValue() 方法实现,该方法直接返回包装的值。
xxx 代表基本数据类型,如:
Integer 的拆箱方法为 intValue()
public int intValue() {
return value;
}
装箱
装箱通过valueOf() 实现,该方法可能会缓存部分值
如:Integer 默认会缓存 [-128, 127]的值,当通过 valueOf 创建一个 在[-128, 127]的 Integer 之后,会缓存该对象,再次创建该值的Integer会直接返回缓存中的对象,不会创建新对象
当 Integer a 和 int b,使用equals() 比较时,会自动装箱,将b封装成一个Integer
public static Integer valueOf(int i) {
//默认情况下,i在[-128, 127]会直接返回缓存中的对象
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}