Integer的"=="问题

版权声明:已经弃坑CSDN,转载随意. https://blog.csdn.net/m0_37961948/article/details/82379522

 Integer 的“ == ”问题

public class IntegerQuestion {
    public static void main(String[] args) {
        Integer f1 = -129, f2 = -129, f3 = -128, f4 = -128;
        Integer f5 = 127, f6 = 127, f7 = 128, f8 = 128;
        System.out.println("-129 == -129 :" + (f1 == f2));
        System.out.println("-128 == -128 :" + (f3 == f4));
        System.out.println("-128 == -128 :" + (f5 == f6));
        System.out.println("-128 == -128 :" + (f7 == f8));
    }
}

/**
结果是
-129 == -129 :false
-128 == -128 :true
 127 ==  127 :true
 128 ==  128 :false
*/

为什么会出现这个结果?和我想象的有些不一样.

我们都知道 Object的“==”是比较地址的,而JVM中已经帮我们申请好了 -128~127的值,当需要使用时,直接引用这个地址,所以-128~127之间所有的Integer对象都是指向堆上的同一块内存。所以使用“==”的结果就是相同.

而不再这个范围的值就需要每次新申请内存,所以两者地址不同,返回false.

猜你喜欢

转载自blog.csdn.net/m0_37961948/article/details/82379522