在-128 至 127 范围内的赋值,Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值能够直接使用==进行 判断,可是这个区间以外的全部数据,都会在堆上产生,并不会复用已有对象,这是一个大坑, 推荐使用 equals 方法进行判断。 spa
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 } }