Java中为啥1000==1000和100==100结果不同?

译文链接:http://www.codeceo.com/article/why-java-1000-100.html
英文原文:Why 1000 == 1000 Returns False, but 100 == 100 Returns True in Java?
翻译作者:码农网 – 小峰

如果你运行下面的代码

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

你会得到

false
true

基本知识:我们知道,如果两个引用指向同一个对象,用==表示它们是相等的。如果两个引用指向不同的对象,用==表示它们是不相等的,即使它们的内容相同。

因此,后面一条语句也应该是false

这就是它有趣的地方了。如果你看去看 Integer.java 类,你会发现有一个内部私有类,IntegerCache.java,它缓存了从-128到127之间的所有的整数数组。

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 integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

所以事情就成了,所有的小整数在内部缓存,然后当我们声明类似Integer c = 100;的时候,它实际上在内部做的是:

Integer i = Integer.valueOf(100);

现在,如果我们去看valueOf()方法,我们可以看到

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

如果值的范围在-128到127之间,它就从高速缓存返回实例。

所以…

Integer c = 100, d = 100;

变量cd指向了同一个对象。

这就是为什么我们写

System.out.println(c == d);

我们可以得到true

现在你可能会问,为什么这里需要缓存?

合乎逻辑的理由是,在此范围内的“小”整数使用率比大整数要高,因此,使用相同的底层对象是有价值的,可以减少潜在的内存占用。

然而,通过反射API你会误用此功能。

import java.lang.reflect.Field;

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);
    // 第132个元素为:-128+132 = 4
    // 第133个元素为:-128+133 = 5
    newCache[132] = newCache[133];

    int a = 2;
    // 2+2 = 4,则将IntegerCache中第132个值赋给b,即5
    int b = a + a;
    System.out.printf("%d + %d = %d", a, a, b);
}

输出结果

2 + 2 = 5
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。