Integer == 與 eques的坑以及避免NEP

先看一段代碼

  public static void main(String[] args) {
        Integer a = 100, b = 100, c = 600, d = 600;
        System.out.println(a == b);
        System.out.println(c == d);
    }

結果是
在這裏插入圖片描述
查看源碼得知,以上四個變量都進行了自動裝箱

   public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

而且,當參數值在IntegerCache範圍之內時,返回的是已有的對象

看一下IntegerCache

 private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHigh
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章