1. 如何对 List<Integer> result = new ArrayList<>(nums.length) result某个索引值进行修改?
答案是不能,除非通过反射。
原因是Integer中对value 的保存是不可修改的
private final int value;
2. 如何交换两个Integer类型的值?
public static void main(String[] args) {
Integer i = 1;
Integer j = 2;
swap(i, j);
System.out.println("i=" + i + "----------j=" + j);
}
private static void swap(Integer i, Integer j) {
try {
int temp = i;
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.set(i, j);
field.set(j, temp);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
以上方式输出:
i=2----------j=2
而如果
Integer i = 128;
Integer j = 129;
输出正确:
i=129----------j=128
原因分析:
Integer 中有Integer 数组缓存,此缓存通过静态类IntegerCache来实现
static final Integer cache[];
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);
}
图示解释如下:
3. Practise
Integer testA = 1;
Integer testB = 1;
Integer testC = 128;
Integer testD = 128;
System.out.println("testA=testB " + (testA == testB) + ",\ntestC=testD " + (testC == testD));
输出:
testA=testB true,
testC=testD false