自動裝箱與自動拆箱的一些問題

今天打算複習一下Java基礎,之前學的太快速了,現在暑假,好好把那些細節看一下

複習到自動裝箱和自動拆箱的時候,這裏有個很有趣的現象

  1. Integer n1 = 100;   
  2. Integer n2 = 100;    
  3. System.out.println(n1 == n2);      
  4.  
  5. Integer n3 = 200;    
  6. Integer n4 = 200;    
  7. System.out.println(n3 == n4);   

你們猜猜結果是什麼  第一個是true,第二個是false。有趣吧。

其實它們是相當於

  1. Integer n1 = Integer.valueOf(100);      
  2. Integer n2 = Integer.valueOf(100);     
  3. System.out.println(n1 == n2);    
  4.  
  5. Integer n1 = Integer.valueOf(200);      
  6. Integer n2 = Integer.valueOf(200);     
  7. System.out.println(n1 == n2);     
  8.    

所以那個valueOf()就是問題的關鍵啦,看一下這個函數的源碼

  1. /**    
  2.   * Returns an {@code Integer} instance representing the specified    
  3.   * {@code int} value.  If a new {@code Integer} instance is not    
  4.   * required, this method should generally be used in preference to    
  5.   * the constructor {@link #Integer(int)}, as this method is likely    
  6.   * to yield significantly better space and time performance by    
  7.   * caching frequently requested values.    
  8.   *    
  9.   * This method will always cache values in the range -128 to 127,    
  10.   * inclusive, and may cache other values outside of this range.    
  11.   *    
  12.   * @param  i an {@code int} value.    
  13.   * @return an {@code Integer} instance representing {@code i}.    
  14.   * @since  1.5    
  15.   */    
  16.  public static Integer valueOf(int i) {     
  17.      assert IntegerCache.high >= 127;     
  18.   if (i >= IntegerCache.lo&&i<=IntegerCache.high)          
  19.  return IntegerCache.cache[i + (-IntegerCache.low)];     
  20.      return new Integer(i);     
  21.  }    

所以我們知道了,對於-128到127之間的數,Integer.valueOf(99)返回的是緩存中的對象,所以兩次調用valueOf返回的是同一個對象,故結果是true.而Integer.valueOf(199)返回的則是重新實例化的對象,故結果是false.

 

自動拆箱

 

  1. Integer n1 = 10;  
  2. int t1 = n1;  
  3. Integer n2 = 10;  
  4. int t2 = n2;  
  5. System.out.println(t1 == t2); 

 

  1. Integer n1 = 199;  
  2. int t1 = n1;  
  3. Integer n2 = 199;  
  4. int t2 = n2;  
  5. System.out.println(t1 == t2); 

兩次的結果是true。

 

所以我們要注意自動裝箱時候數值的範圍的選擇~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章