目录
1、装箱
Integer a = 100;// Integer.valueOf(100); 装箱
2、拆箱
int c = Integer.valueOf(100);// Integer.valueOf(100).intValue(); 拆箱
3、整型缓存池
Integer 缓存是 Java 5 中引入的一个有助于节省内存、提高性能的特性。
Integer中有个静态内部类IntegerCache,里面有个cache[],也就是Integer常量池,常量池的大小为一个字节(-128~127)。
Integer代码里的Integer缓存池定义和初始化代码:
/**
* 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() {}
}
通过源码可以看出Integer的缓存池大小是可以调整的,通过设置启动参数-XX:AutoBoxCacheMax=<size> 来调整Integer的缓存池大小
Integer的valueOf方法代码:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
所有整数类型的类都有类似的缓存机制:
有 ByteCache 用于缓存 Byte 对象
有 ShortCache 用于缓存 Short 对象
有 LongCache 用于缓存 Long 对象
Byte,Short,Long 的缓存池范围默认都是: -128 到 127。
除了 Integer 可以通过参数改变范围外,其它的都不行。
4、代码测试装箱拆箱
测试代码:
Integer a = 100;// Integer.valueOf(100); 装箱
Integer b = null;
int c = Integer.valueOf(100);// Integer.valueOf(100).intValue(); 拆箱
Integer d = 1000;
Integer e = 1000;
Integer f = 100;
System.out.println("a == f " + (a == f));// true 虽然比较的是两个对象,但是jdk5.0后,对-128-127这个范围内的整型对象进行了缓存,a和f实际指向的是一个对象
System.out.println("a.equals(f) " + a.equals(f));// true 比较值
System.out.println("d == e " + (d == e));// false 比较的是两个对象的地址,两个对象的值虽然相同,但是由于数值超出了-128-127这个范围,d和e是两个不同的对象
System.out.println("d.equals(e) " + d.equals(e));// true 比较值
System.out.println("a == c " + (a == c));// true 进行拆箱比较了
System.out.println("c == b " + (c == b));// java.lang.NullPointerException 包装类和基本类型比较的时候会调用b.intValue() 把b拆箱后进行比较,b为null所以报错
// java.lang.NullPointerException a是包装类型,但是调用a.intValue()之后就变成了 包装类和基本类型比较,这时候依旧会调用b.intValue() 把b拆箱后进行比较,b为null所以报错
System.out.println("a.intValue() == b " + (a.intValue() == b));
通过反编译看装箱拆箱,以下是反编译后的代码:
Integer localInteger1 = Integer.valueOf(100);
Object localObject = null;
int i = Integer.valueOf(100).intValue();
Integer localInteger2 = Integer.valueOf(1000);
Integer localInteger3 = Integer.valueOf(1000);
Integer localInteger4 = Integer.valueOf(100);
System.out.println(new StringBuilder().append("a == f ").append(localInteger1 == localInteger4).toString());
System.out.println(new StringBuilder().append("a.equals(f) ").append(localInteger1.equals(localInteger4)).toString());
System.out.println(new StringBuilder().append("d == e ").append(localInteger2 == localInteger3).toString());
System.out.println(new StringBuilder().append("d.equals(e) ").append(localInteger2.equals(localInteger3)).toString());
System.out.println(new StringBuilder().append("a == c ").append(localInteger1.intValue() == i).toString());
System.out.println(new StringBuilder().append("c == b ").append(i == localObject.intValue()).toString());
System.out.println(new StringBuilder().append("a.intValue() == b ").append(localInteger1.intValue() == localObject.intValue()).toString());
5、注意
开发中比较包装类不要用 d == e ,这会出现非预期的结果;也不要用 a.intValue() == b ,这会出现空指针异常;可以在保证 a 不为null 的前提下使用a.equals(b)。