知道Integer屬於對象類型的,因此在比較的時候直接使用 Integer實體.equals() 來進行比較。能夠忽然發如今數字小的時候直接使用== 也能夠判斷是正確的。後來搜索發現原來緣由是這樣:web
先看段代碼:orm
public static void main(String[] arg){對象
Integer a=300000;內存
Integer b=300000;it
Integer c=30;搜索
Integer d=30;webkit
System.out.println(a.equals(b));數據
System.out.println(a==b); //falsestatic
System.out.println(a==300000);數字
System.out.println(d.equals(c));
System.out.println(d==c);
System.out.println(d==30);
}
打印結果說明-128 到 127的數值,怎麼比較都同樣,其它的只有equals時才相等.
Java自動裝箱是對於從 -128 到 127 之間的信息值,它們在被裝箱爲對象數據後會在內存中被重用,也就是對於相同的值,返回的是同一個對象.直接與數值比較時,大概是拆箱比較了,就跟 int的比較同樣了,因此仍是相等的.