因为类中有方法,使用包装类可以帮助我们实现不同数据类型之间的转换。
装箱/装包装箱也叫装包,其实就是把简单数据类型转换成包装类型。
自动装箱 public static void main(String[] args) {
int i = 10;
Integer a = i;
}
这就是自动装箱
手动装箱 public static void main(String[] args) {
int i = 10;
Integer a = Integer.valueOf(i);
}
这就是手动装箱
拆箱/拆包拆箱也叫拆包,其实就是把包装类型转换成简单数据类型
自动拆箱public static void main(String[] args) {
Integer a = 10;
int i = a;//拆包
}
这就是自动拆箱
手动拆箱 public static void main(String[] args) {
Integer a = 10;
int i = a.intValue();
}
这就是手动拆箱
注意public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
System.out.println(a == b);
}
输出为true
public static void main(String[] args) {
Integer a = 200;
Integer b = 200;
System.out.println(a == b);
}
但是它的输出为false,我们主要看valueof的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里的low是-128,high是127,所以我们可以理解成当输入的i值是在-128<=i<=127时,直接返回的是数组里的值,当不在这个范围时,new新的对象。所以100时为true,200时为false。



