# Hold住面试官之Integer Cache

2019/04/04 09:30

#### 前言

public class IntegerDemo {
public static void main(String[] args) {
Integer numA = 127;
Integer numB = 127;

Integer numC = 128;
Integer numD = 128;

System.out.println("numA == numB : "+ (numA == numB));
System.out.println("numC == numD : "+ (numC == numD));
}
}

numA == numB : true
numC == numD : false

What？这个输出结果怎么跟以往的认知有所出入呢？在我们的代码“Integer numA = 127”中，编译器会把基本数据的“自动装箱”(autoboxing)成包装类,所以这行代码就等价于“Integer numA = Integer.valueOf(127)”了,这样我们就可以进入valueOf方法查看它的实现原理。

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

//Integer静态内部类
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 class IntegerDemo {
public static void main(String[] args) {
Integer numA = new Integer(127);
Integer numB = new Integer(127);

Integer numC = new Integer(128);
Integer numD = new Integer(128);

System.out.println("numA == numB : "+ (numA == numB));//false
System.out.println("numC == numD : "+ (numC == numD));//false
}
}

Redis的正确使用姿势

0
0 收藏

0 评论
0 收藏
0