在-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 } }