為什么Java中1000==1000為false,而100==100為true?

這是一個(gè)挺有意思的討論話題。

如果你運(yùn)行下面的代碼:

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

你會(huì)得到

false
true

基本知識(shí):我們知道,如果兩個(gè)引用指向同一個(gè)對(duì)象,用 == 表示它們是相等的。如果兩個(gè)引用指向不同的對(duì)象,用 == 表示它們是不相等的,即使它們的內(nèi)容相同。

因此,后面一條語(yǔ)句也應(yīng)該也是 false 。

這就是它有趣的地方了。如果你看去看 Integer.java 類,你會(huì)發(fā)現(xiàn)有一個(gè)內(nèi)部私有類,IntegerCache.java,它緩存了從 - 128 到 127 之間的所有的整數(shù)對(duì)象。

所以事情就成了,所有的小整數(shù)在內(nèi)部緩存,然后當(dāng)我們聲明類似——

Integer c = 100;

的時(shí)候,它實(shí)際上在內(nèi)部做的是:

Integer i = Integer.valueOf(100);

而Integer類中的valueOf方法是這樣的

/**
  * Returns an {@code Integer} instance representing the specified
  * {@code int} value.  If a new {@code Integer} instance is not
  * required, this method should generally be used in preference to
  * the constructor {@link #Integer(int)}, as this method is likely
  * to yield significantly better space and time performance by
  * caching frequently requested values.
  *
  * This method will always cache values in the range -128 to 127,
  * inclusive, and may cache other values outside of this range.
  *
  * @param  i an {@code int} value.
  * @return an {@code Integer} instance representing {@code i}.
  * @since  1.5
  */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

注釋的大致意思是

返回表示指定int值的Integer實(shí)例。 如果不需要新的Integer實(shí)例,則通常應(yīng)優(yōu)先使用此方法而不是構(gòu)造函數(shù)Integer(int) ,因?yàn)榇朔椒ㄍㄟ^(guò)緩存頻繁請(qǐng)求的值可能會(huì)產(chǎn)生明顯更好的空間和時(shí)間性能。 此方法將始終緩存 -128 到 127(含)范圍內(nèi)的值,并且可能緩存此范圍之外的其他值

所以…當(dāng)定義的值在-128到127之間時(shí), 使用的是同一個(gè)對(duì)象. 所以 c==d的結(jié)果為 true

Integer c = 100, d = 100;
System.out.println(c == d);  // true

同樣的 Long, Short 中也有緩存cache. 值也是 -128~127

例如在實(shí)體類中, 主鍵ID的類型為Integer, 在集合中需要去重. 則需要重寫實(shí)體類中的equals和hashCode方法.這時(shí)候就不能使用 == 比較兩個(gè)值是否相等, 而是使用equals(). 因?yàn)镮nteger中的equals方法會(huì)轉(zhuǎn)為int類型. 源碼如下

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
}

通過(guò)反射 API 你可能會(huì)誤用此功能

運(yùn)行下面的代碼,享受它的魅力吧

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

      Class cache = Integer.class.getDeclaredClasses()[0]; 
      Field myCache = cache.getDeclaredField("cache"); 
      myCache.setAccessible(true);

      Integer[] newCache = (Integer[]) myCache.get(cache); 
      newCache[132] = newCache[133]; 

      int a = 2;
      int b = a + a;
      System.out.printf("%d + %d = %d", a, a, b); // 2 + 2 = 5 ?
}

注意System.out.printf()方法的參數(shù)類型

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容