JDK 1.8 Integer

作者: 阿波罗程序猿 | 来源:发表于2018-07-27 15:53 被阅读0次

只是简单谈谈,不全面覆盖

  1. 关于Integer值的比较。
public static void main(String[] args) {
        Integer i = 1, i1 = 1, j = 190, j1 = 190;
        System.out.println(i.equals(i1));
        System.out.println(j.equals(j1));
        System.out.println("======");
        System.out.println(i == i1);
        System.out.println(j == j1);
        System.out.println("======");
    }

输出:
  true
  true
  ======
  true
  false
  ======

为什么j == j1结果为 false呢?请看下面代码:

  // 这个类是 Integer 的一个内部类,作为 Integer 缓存来使用。Integer 在初始化的时候就已经生成了从 -128到127个数。
  //所以上面的变量 i 与 i1 都是从缓存中拿到的相同的引用,所以它们是相同的。不在这么范围内的数,则是2个不同的引用,所以它们是不等的。
  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() {}
    }

相关文章

网友评论

    本文标题:JDK 1.8 Integer

    本文链接:https://www.haomeiwen.com/subject/njcgmftx.html