JAVA包装类的缓存范围

前两天面试遇到两个关于JAVA源码的问题,记录下来提醒自己。

1.写出下面的输出结果

System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));    --false
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));        --true
System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128"));     --true
System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000"));  --false

当时因为不了解Integer.valueOf(int a)方面底层的实现,所以认为都是进行的对象的==比较,都为false。但是错了正确答案是 false true true false

后面看了源码才知道,原来如果是a的值在-128到127之间的话,是直接从一个Integer [] cache 的数组中取数;如果不再这个范围内才会new Integer对象。

下面是相关的源码:

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

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) {
      int i = parseInt(integerCacheHighPropValue);
      i = Math.max(i, 127);
      // Maximum array size is Integer.MAX_VALUE
      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() {}
}

包装器的缓存:

  • Boolean:(全部缓存)
  • Byte:(全部缓存)
  • Character(<= 127缓存)
  • Short(-128 — 127缓存)
  • Long(-128 — 127缓存)
  • Integer(-128 — 127缓存)
  • Float(没有缓存)
  • Doulbe(没有缓存)

同样对于垃圾回收器来说:

ru:Integer i = 100;

i = null;

这里虽然i被赋予null,但它之前指向的是cache中的Integer对象,而cache没有被赋null,所以Integer(100)这个对象还是存在;然而如果这里是1000的话就符合回收的条件;其他的包装类也是。

原文地址:https://www.cnblogs.com/javatech/p/3650460.html