public class Test2 {
public static void main(String[] args) {
//包装类的"=="运算在不遇到算数运算的情况下不会自动拆箱
//包装类的equals()方法不处理数据转型
//"=="比较的是引用而非引用的值
//当需要对low到high之间的数字进行装包操作时,则直接返回IntegerCache.cache中现成的引用
Integer a = 1;//自动装箱
Integer b = 2;//自动装箱
Integer c = 3;//自动 装箱
Integer d = 3;//直接返回引用 与c引用相同
Integer e = 321;//自动装箱
Integer f = 321;//超过high范围 所以没有使用缓存 使用了自动装箱 与e引用不同
Long g = 3L;
System.out.println(c == d);//未自动拆箱 两者引用相同 所以true
System.out.println(e == f);//未自动拆箱 两者引用不同 所以false
System.out.println(c == (a+b));//自动拆箱 类型相同 值相等 所以true
System.out.println(c.equals(a+b));//自动拆箱 类型相同 值相等 所以true
System.out.println(g == (a+b));//自动拆箱 并类型转换 类型相同且值相等 所以true
System.out.println(g.equals(a+b));//自动拆箱 但不会类型转换 类型不同 所以false
}
}
使用jad反编译工具还原真实代码,可以将编译时自动添加的代码显示出来.如下:
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(2);
Integer c = Integer.valueOf(3);
Integer d = Integer.valueOf(3);
Integer e = Integer.valueOf(321);
Integer f = Integer.valueOf(321);
Long g = Long.valueOf(3L);
System.out.println(c == d);
System.out.println(e == f);
System.out.println(c.intValue() == a.intValue() + b.intValue());
System.out.println(c.equals(Integer.valueOf(a.intValue() + b.intValue())));
System.out.println(g.longValue() == (long)(a.intValue() + b.intValue()));
System.out.println(g.equals(Integer.valueOf(a.intValue() + b.intValue())));