关于java自动拆箱,装箱的陷阱

/**
 * 自动拆箱装箱案例
 * @author Administrator
 *
 */
public class ChaiXiang {
	public static void main(String[] args) {
		Integer a = 1;
		Integer b = 2;
		Integer c = 3;
		Integer d = 3;
		Integer e = 321;
		Integer f = 321;
		Long g = 3l;
		System.out.println(c == d);
		System.out.println(e == f);
		System.out.println(c == (a + b));
		System.out.println(c.equals(a + b));
		System.out.println(g == (a + b));
		System.out.println(g.equals(a + b));
	}
}

运行结果为:

true
false
true
true
true
false

为什么第二个为false,第一个为true?为什么最后一个为false

让我们看一下Integer的源码

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

默认IntegerCache.low 是-128,Integer.high是127,如果在这个区间内,他就会把变量i当做一个变量,放到内存中;但如果不在这个范围内,就会去new一个Integer对象,所以,这就是第一个为true的原因。

第二个为false是因为包装类的“==”运算在没有算术运算的情况下不会自动拆箱,并且创建了一个新的对象。

第三,四,五因为“==”运算有算术运算所以自动拆箱为int类型,所以他们的结果为true

最后一个为false是因为equals方法不会处理数据类型转换的关系

猜你喜欢

转载自blog.csdn.net/qq594913801/article/details/79494830