java 對象和基本數據類型 “==”區別


“==”比較的是地址,牢記。
1。對象。integer 是對象
Integer i1 = 20;
Integer i2 = 20 ;
System.out.println(i1 == i2); // true
Integer i3 = 200;
Integer i4 = 200 ;
System.out.println(i3 == i4); // false

 

原因:Integer i1 = 20; 其實是一個自動裝箱的過程,編譯器會自動展開成Integer i = Integer.valueOf(20);詳情可以看Integer.valueOf的源代碼,可以看到參數的值在IntegerCache.low(默 認-128) 到 IntegerCache.high(默認127)范圍內時(比如20),會從IntegerCache.cache中直接取(此處參考Integer的 內部類IntegerCache的源代碼,如果不配置的話,默認是cache存儲-128到127的Integer),所以取到的都是同一個 Integer的對象,因此相同。而200不在-128到127范圍內,所以會new 一個新的Integer,故不相同。
 
2.類型。int 是基本數據類型
 
int i1=20;
int i2=20;
System.out.println(i1==i2);//true
int i3=200;
int i4=200;
System.err.println(i3==i4);//true

原因:i1 開辟了一個內存空間,對於i2來說,jvm先在內存中尋找是否有20的地址,有就給i2賦值,也就是讓i2也指向20那塊地址。所以返回的是TRUE.

3.

String str1 = "hello";
String str2 = "he" + new String("llo");
System.err.println(str1 == str2);

 返回的是false。

原因:因為str2中的llo是新申請的內存塊,而==判斷的是對象的地址而非值,所以不一樣。如果是String str2 = str1,那么就是true了。

 
 
 
 


免責聲明!

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



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