深入jvm虚拟机看到语法糖-自动拆装箱章节的有趣问题
2017-08-14 本文已影响0人
炫迈哥
public class Test {
public static void main(String[] args){
Integer a = 1;
Integer b = 3;
Integer c = 4;
Integer d = 1;
int i = 278;
Integer e = 278;
Integer f = 278;
Long g = 4;
System.out.println(c == a+b);
System.out.println(a == d);
System.out.println(c > a + d);
System.out.println(g == a+b);
System.out.println(e == f);
System.out.println(e == i);
System.out.println(g==d);
}
}
输出结果
true
true
true
true
false
true
true
解析
- 声明1, 两个包装类进行==比较时,会直接比较两个包装类的地址,包装类跟基本类型==比较时,会先拆箱再比较
- 声明2, Integer的实现有一个内部类
IntegerCache
,会缓存-128-127之间的数值,当装箱时会直接从cache拿一个对象出来。 - 声明3, 两个包装类进行==比较时,如果有进行运算+,-乘除等,也会拆箱,所以c == a+b成立