public class Student {
public static void main(String[] args) {
//自动装箱
Integer a = 6;
//自动拆箱
int b = a;
}
}
上边两行代码就是自动装箱和拆箱,简单来说就是:装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。
下面我们来看看需要装箱拆箱的类型有哪些:也就是基本数据类型对应的包装类:
下面通过几个例子了解一下包装类。
第一个:看到这个程序,第一时间想这还用判断?肯定是错,因为==如果是对象则比较地址,现在两个新对象肯定分配的地址不一样呀。但是结果是true。
public static void main(String[] args) {
//自动装箱
Integer a = 6;
Integer b = 6;
System.out.println(a == b);
}
打开Integer源码发现:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,//这个范围内,自动放在常量池中
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
This method will always cache values in the range -128 to 127,//这个范围内,自动放在常量池中,所以是一个地址,当然是true。
第二个:当包装类和基本数据类型做比较,则包装类自动拆箱:
public static void main(String[] args) {
//自动装箱
Integer a = 128;
int b = 128;
System.out.println(a == b);
}