java基础复习

Integer a = 127; // 将整形127装箱对象
Integer b = 127; // 同上
        
System.out.print( a==b ); // true
System.out.print(a.equals(b)); // true

Integer a = 127 实际为Integer a =Integer.valueOf(127);

Integer a = 128;
Integer b = 128;
        
System.out.print( a==b ); // false 
System.out.print(a.equals(b)); // true

127与128 == 运行结果不同的原因在于,当值为小于一个字节时不会再占用另外一个空间,也就是说第一个代码块中a与b占用的是同一块内存,所以为true,但是第二块代码中则不是

源码:
public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)  // 没有设置的话,IngegerCache.high 默认是127
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}
原文地址:https://www.cnblogs.com/orlion/p/4787068.html