Integer简单学习
Integer 缓存: IntegerCache
/**
* 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() {}
}
- 在首次使用时会申请内存空间,存放 [-127, high] 区间的数字,其中
high
可被配置 - 当发生“自动装箱时”优先查看数字是否在 cache 范围中,如果在则使用 cache 中的数据
- 可见,默认缓存 [-128, 127] 区间的数字
三两例
1、使用区间内的数字
// [-128, 127]
Integer c1 = 127;// 使用 IntegerCache 中的数字
Integer c2 = new Integer(127); // new 的,占用内存空间,是对象
System.out.println(c1 == c2); // false
new Integer(xxx)
会直接创建对象,不发生自动装箱的动作
2、使用区间外的数字
Integer b1 = 188;
Integer b2 = new Integer(188); // 相当于 “ = 188;”
Integer b3 = 188;
System.out.println(b1 == b2);// false,188 不在 IntegerCache 中,是 new 的
System.out.println(b1 == b3);// false,两者都不在 IntegerCache 中,都是 new 的
System.out.println(b1.equals(b2));// true, int 数值比较!
使用 Integer i = xx;
,如果 xx
不在 [-128, 127]
内,右半部分会进行 new Integer(xx);
3、面试题⭐
Integer a1 = Integer.parseInt("123");// 右边先返回 int 类型,再包装成 Integer
Integer a2 = Integer.valueOf("123").intValue();
// 1. valueOf 返回 Integer
// 2. intValue 返回 int 类型
System.out.println(a1 == a2);// true, 以上两句最终的 Integer 变量都是先得到int类型数值,再自动装箱得到的
System.out.println(a1.equals(a2));// 值比较
沉舟侧畔千帆过,病树前头万木春。