Integer类

1. Integer缓冲区

  • Java预先创建了256个(-128~127)常用的整数包装类型对象。
  • 在实际应用当中,对已创建的对象进行复用。

对应源码:

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

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() {}
}


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

所以,

new Integer(100) == Integer(100);    // false,两个对象均为实例化对象,会在堆中新建对象,在栈中进行地址引用。所以两个对象的引用地址不同。

但是,

Integer a = 100;
Integer b = 100;
a == b;    // true,自动装箱,此时并不是实例化对象,并不会新建对象,而是对已有的在Integer缓冲池中对象进行复用,并在栈中进行地址引用。此时二者地址相同,实际上为同一个对象。

并且,

Integer a = 200;
Integer b = 200;
a == b;    // false,自动装箱,由于这个数并不在Integer缓冲池中,故均会进行实例化,所以地址不同。

2. equals()

Integer类下的equals()的方法被重写,不再是比较地址,而是比较数值。

源码如下:

public boolean equals(Object obj) {
  if (obj instanceof Integer) {
    return value == ((Integer)obj).intValue();
  }
  return false;
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:52

results matching ""

    No results matching ""