JAVA Integer值的范圍


原文出處:http://hi.baidu.com/eduask%C9%BD%C8%AA/blog/item/227bf4d81c71ebf538012f53.html

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
   }
}

 

  這是什么原因呢?
  1。java在編譯的時候 Integer a = 100; 被翻譯成-> Integer a = Integer.valueOf(100);
  2。比較的時候仍然是對象的比較
  3。在jdk源碼中

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管理區
} 

  而

private static class IntegerCache { 
  private IntegerCache(){} 
  static final Integer cache[] = new Integer[-(-128) + 127 + 1]; //開辟-128到127的內存區。有0的位置哦
  static { 
    for(int i = 0; i < cache.length; i++) 
      cache[i] = new Integer(i - 128); //為內存區的數組每個對象賦值
    } 
  } 

  這邊是java為了提高效率,初始化了-128--127之間的整數對象,所以在賦值在這個范圍內都是同一個對象。

  

  再加一句
  Integer a = 100;
  a++;
  //這邊a++是新創建了一個對象,不是以前的對象。

    public static void main(String []args) {
        Integer a = 100;
        Integer b = a;//此時b指針指向值為100的堆地址  即a的堆地址,a==b成立
        a++;//此時a指向的值發生變化為101,a指針指向101的堆地址。而b任然指向100
        System.out.println(a==b);//false
    }

 

 


 


免責聲明!

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



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