Integer應該用==還是equals


問題引出:“Integer應該用==還是equals”

討論這個問題之前我們先放一段代碼

public static void main(String[] args) {

Integer a1 = 2;
Integer a2 = 2;
System.out.println(a1==a2); //true
System.out.println(a1.equals(a2)); //true

Integer a3 = 127;
Integer a4 = 127;
System.out.println(a3==a4); //true
System.out.println(a3.equals(a4)); //true

Integer a5 = -128;
Integer a6 = -128;
System.out.println(a5==a6); //true
System.out.println(a5.equals(a6)); //true
/**
* ----
* */
Integer a11 = 128;
Integer a21 = 128;
System.out.println(a11==a21); //false
System.out.println(a11.equals(a21)); //true


Integer a1111 = -129;
Integer a2111 = -129;
System.out.println(a1111==a2111);//false
System.out.println(a1111.equals(a2111)); //true
}

上述代碼可以看出 值相同的Integer對象做==操作,有的是true,有的是false,而equals操作的一直是true,為什么會出現這種情況?

我們首先解釋==操作,為什么有的是true,有的是false:

  討論之前:先要知道對象的==操作,比較的是對象的地址

   對於 Integer var = ? -128 127 范圍內的賦值, Integer 對象是在IntegerCache.cache 產生,會復用已有對象,比如a1和a2,他們都是指向的同一塊內存空間

對象的==操作,比較的是"地址",所以對於-128 至 127 范圍內的Integer 對象,值相同的integer對象都是指向的同一塊內存空間,所以這個區間內的 Integer 值可以

直接使用==進行判斷,但是這個區間之外的所有數據,都會在堆上產生,並不會復用已有對象,這是一個大坑

 我們再來解釋equals,為什么一直是true:

對象的equals,比較的是對象的值,所以只要值相同的Integer對象,使用equals比較的結果,都會是true

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM