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

猜你喜欢

转载自blog.csdn.net/leisure_life/article/details/103699915