Integer ,==,int 的使用


面試比較常見的題目:自己也經常忘記,所以就記下來了

上代碼:

1 Integer a = 1000,b=1000;  
2 Integer c = 100,d=100;  
3   
4 System.out.println(a==b);  
5 System.out.println(c==d);

輸出的正確結果分別是  falsetrue

原因:看Integer.java類

public static Integer valueOf(int i) {  
      return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];  
  }  
  
  /** 
   * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing 
   */  
  private static final Integer[] SMALL_VALUES = new Integer[256];  
  
  static {  
      for (int i = -128; i < 128; i++) {  
          SMALL_VALUES[i + 128] = new Integer(i);  
      }  
  }

當聲明Integer a=100 的時候,會進行自動裝箱操作,即調用 valueOf() 把基本數據類型轉換成Integer對象,valueOf()方法中可以看出,

程序把 -128—127之間的數緩存下來了(比較小的數據使用頻率較高,為了優化性能),所以當Integer的對象值在-128—127之間的時候是

使用的緩存里的同一個對象,所以結果是true,而大於這個范圍的就會重新new對象。

 

2. Integer 和 int

上代碼:

Integer a = new Integer(1000);  
int b = 1000;  
Integer c = new Integer(10);  
Integer d = new Integer(10);  
System.out.println(a == b);  
System.out.println(c == d); 

正確答案:true ,false

解析:

第一個:值是1000,肯定和緩存無關,但是b的類型是int,當int和Integer進行 == 比較的時候 ,java會將Integer進行自動拆箱操作,

再把Integer轉換成int,所以比較的是int類型的數據,   so 是true

第二個:雖然值是10 在緩存的范圍內,但是 c,d都是我們手動new出來的,不需要用緩存, so 是false

 

 

 

 

---------------------------------------------------------------------阿紀----------------------------------------------------------------------

 


免責聲明!

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



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