【问题标题】:What are the benefits of IntegerCache while using Integer? [duplicate]使用 Integer 时 IntegerCache 有什么好处? [复制]
【发布时间】:2013-10-28 11:21:54
【问题描述】:

Integer class 中,有private static class IntegerCache

这个类有什么用?

使用Integer有什么好处?

【问题讨论】:

    标签: java integer


    【解决方案1】:

    IntegerCache 缓存 -128 到 +127 之间的值以优化自动装箱。

    您可以使用-XX:AutoBoxCacheMax=NEWVALUE-Djava.lang.Integer.IntegerCache.high=NEWVALUE 设置大于127 的上限

    【讨论】:

      【解决方案2】:

      -128 和 127 之间的值被缓存以供重复使用。这是flyweight pattern 的一个示例,它通过重用不可变对象来最小化内存使用量。


      除了优化之外,此行为是 JLS 的一部分,因此可以依赖以下内容:

      Integer a = 1;
      Integer b = 1;
      Integer c = 999;
      Integer d = 999;
      System.out.println(a == b); // true
      System.out.println(c == d); // false
      

      【讨论】:

        【解决方案3】:

        看看它的实现:

        private static class IntegerCache {
           static final int high;
           static final Integer cache[];
           static {
              final int low = -128;
              int h = 127;
              if (integerCacheHighPropValue != null) {
                  int i = Long.decode(integerCacheHighPropValue).intValue();
                  i = Math.max(i, 127);
                  h = Math.min(i, Integer.MAX_VALUE - -low);
              }
              high = h;
              cache = new Integer[(high - low) + 1];
              int j = low;
              for(int k = 0; k < cache.length; k++)
              cache[k] = new Integer(j++);
           }
           private IntegerCache() {}
        }
        

        256 个值被缓存以供再次使用,它们将在您创建第一个 Integer 对象时加载。

        因此,当您使用 == 运算符检查 [-127,128] 范围内两个 Integers 的相等性时,您会得到它,就好像您在比较两个 ints 时一样。但是,如果您使用== 比较超出此范围的两个Integer,您将得到false,即使它们具有相同的值。

        【讨论】:

          猜你喜欢
          • 2011-03-16
          • 1970-01-01
          • 2019-08-22
          • 2015-11-10
          • 1970-01-01
          • 2011-07-22
          • 2013-06-01
          • 2019-07-16
          • 2014-01-13
          相关资源
          最近更新 更多