Integer 類在對象中包裝了一個基本類型 int 的值。
有一個陷阱存在,經常出現在面試題中,情況如下面代碼
public class IntegerDemo { public static void main(String[]args){ Integer a = 200; Integer b = 200; System.out.println(a==b);//false System.out.println(a.equals(b));//true //數據在byte范圍內,JVM不會從新new對象 Integer aa = 127; Integer bb = 127; System.out.println(aa==bb);//true System.out.println(aa.equals(bb));//false Integer aaa = 128; Integer bbb = 128; System.out.println(aaa==bbb);//false System.out.println(aaa.equals(bbb));//true } }
在0~127范圍內,JVM不會從新分配對象。這時直接比較兩個數值相等的對象時,答案為true.
而其他范圍內,需要重新創建對象,這時直接比較兩個數值相等對象,是在比較兩個對象的引用地址,這時答案為false。
轉載地址:http://blog.csdn.net/qq_34114951/article/details/76034562