java Integer判等的大坑

在-128 至 127 范围内的赋值,Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行 判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑, 推荐使用 equals 方法进行判断。 

public class Program {
    public static void main(String[] args) {
        Integer a1 = 1;
        Integer b1 = 1;
        System.out.println(a1 == b1);        // true
        System.out.println(a1.equals(b1));    // true
        System.out.println(a1 == 1);        // true

        Integer a2 = 128;
        Integer b2 = 128;
        System.out.println(a2 == b2);        // false
        System.out.println(a2.equals(b2));    // true
        System.out.println(a2 == 128);        // true
    }
}
原文地址:https://www.cnblogs.com/mousewheel/p/8341311.html