Java integer 的取值范圍


package com.test;
public class Test {
   public static void main(String []args) {
     Integer a = 100;//此處若使用new,則==值必為false
     Integer b = 100;
     System.out.println(a==b);//true

     Integer c = 150;

     Integer d = 150;

     System.out.println(c==d);//false

   }
}
打印結果很顯然。如果換成 127 >= var >= -128 之外的整數就打false了。
這是什么原因呢?
1、java在編譯的時候 Integer a = 100; 被翻譯成-> Integer a = Integer.valueOf(100);

 

 

public static Integer valueOf(int i) { 
final int offset = 128; 
if (i >= -128 && i <= 127) { // must cache 
return IntegerCache.cache[i + offset]; //符合值范圍時候,進入也創建好的靜態IntergerCache,i+offset的值表示去取cache數組中那個下標的值

return new Integer(i); //當不符合-128 127值范圍時候。記住用的:new,開辟新的內存空間,不屬於IntergerCache管理區


免責聲明!

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



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