Java自动装箱和自动拆箱的理解

Java自动装箱和自动拆箱的理解

1、代码

public class AutoBoxing {
    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); // 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
    }
}

2、运行结果

true
false
true
true
true
false

3、结果分析

首先需要明确Integer中==和equals方法的区别,==比较对象的地址,equals方法被Integer包装对象重写过,所以比较的是对象的包装的值。

(1)为什么c == d 为true,而e == f为false?

答:因为Integer.valueOf()函数,包装位于-128-127之间的数时,会自动添加到运行时常量池中。创建缓冲。

简化源码可以表示为:

public static Integer valueOf(int i) {   
    if (i >=-128 && i <= 127)        
        return IntegerCache.cache[i + (-IntegerCache.low)];
    //如果装箱时值在-128到127之间,之间返回常量池中的已经初始化后的Integer对象。
    return new Integer(i);
    //否则返回一个新的对象。
}
原文链接:https://blog.csdn.net/u013309870/article/details/70229983

除此之外,还需要明确:自动拆箱处理==时,如果等式两边不涉及运算符号时,不会自动拆箱

(2)为什么 g.equals(a + b) 为false?

答:因为包装类的equals方法不处理类型转换关系!

猜你喜欢

转载自www.cnblogs.com/doubest/p/12966514.html
今日推荐