(面试题)关于Integer的比较以及==和equals的区别

**先上段代码

public class Test03 {

    public static void main(String[] args) {
        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

        System.out.println(f1 == f2);//返回true
        System.out.println(f1.equals(f2));//返回true

        System.out.println(f3 == f4);//返回false
        System.out.println(f3.equals(f4));//返回true
    }
}

***解释原因

我们先要了解Integer自动封装int类型数据的底层代码:

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

在Integer的代码中IntegerCache.low= - 128 ,IntegerCache.high = 127。当需要封装的数值不在-128~127之间时会new Integer。如果在范围内就直接返回Integer缓存中的对应数字。

要知道,**new出的两个对象地址不同;而返回的缓存中的数字地址相同

**对于==比较的是两个对象的地址,而equals比较的是内容。

所以f1==f2返回true,而f3==f4返回false;

f1.equals(f2)返回true,f3.equals(f4)返回true;

猜你喜欢

转载自blog.csdn.net/xiaoshuo566/article/details/82898885