举例:
Integer x = new Integer(4);
JDK1.5以后,简化了定义方式。,可以直接写成:
Integer x = 128;//自动装箱。通过valueOf,但注意 127>x>-128时装箱时候,指定一个数组进行缓存装箱对象。
自动装箱:程序在应该使用对象的地方,使用了基本数据类型的数据,编译器把该数据自动包装成包装类的对象。
x = x + 5;//自动拆箱。通过intValue方法拆箱,让值进行相加,再进行装箱给X对象。
自动拆箱:程序在应该使用基本数据类型的地方,使用了包装类对象的数据, 编译器把该对象自动进行拆箱,从中去除所包含的基本数据类型。
int x1 = 8;
Integer x2 =8;//new Integer(8);
Integer x3 =8;//new Integer(8)
Integer x6 = 128;//new Integer(128);
Integer x7 = 128;//new Integer(128)
Integer x4 = new Integer(8);
Integer x5 = new Integer(8);
/*判断打印的是true or false?*/
System.out.println(x1 == x2);//true 调用值进行对比//x2.intValue
System.out.println(x1 == x4);//true 调用值进行对比//x4.intValue
//aload_2==aload_3 //未调用intValue进行拆箱
//x2 == x3 进行对比是i >= -128 && i <= 127 判断未true,其他未false
System.out.println(x2 == x3);//true 对象对比,即指向堆内地址对比。 调用valueOf(int i)下IntegerCache.cache[i + (-IntegerCache.low)]
System.out.println(x6 == x7);//fasle 对象对比 。调用valueOf(int i)下new Integer(i)
System.out.println(x4 == x5);//flase 对象对比 。
System.out.println(x2 == x4);//flase 对象对比 。
/*