自动装箱过程是通过调用包装类的valueOf()方法实现的,二自动拆箱过程是通过调用包装类的xxxValue()方法实现的(xxx代表对应的基本数据类型,如intValue,doubleValue等)。
package demo06;
public class TestWrapper2 {
public static void main(String[] args) {
//1.自动装箱和自动拆箱
Integer in = 5;
Integer in2 = new Integer(5);//valueOf()
int i = in2;
int i2 = in2.intValue();
//2.== equals
Integer in3 = new Integer(56);
Integer in4 = new Integer(56);
System.out.println(in3==in4);//false
System.out.println(in3.equals(in4));//true
Integer in5 = 25;
Integer in6 = 25;
System.out.println(in5==in6);//true
System.out.println(in5.equals(in6));//true
Integer in7 = 256;
Integer in8 = 256;
System.out.println(in7==in8);//false
System.out.println(in7.equals(in8));//true
}
}
Integer类提供了一个静态内部类IntegerCache,对于定义一个静态数组cache,长度为256,赋值为-128到127。对于自动装箱时如果是-128到127范围内的数据,
直接获取数组的指定值;对于中国范围之外的数据,通过new Integer()重新创建对象,这么做的目的是提高效率。