我们都知道Integer是int的封装类,提供了一些类型转换等工具方法,有一个-128-127的缓存,而且是final的。
-----------------------------
干货:
Integer是final 的,因此对Integer的操作返回的都是另一个新对象,而不是修改原来的值。
Integer的值存在value属性中,Integer的hashcode就是value值。
Integere重写了quals方法,equals()是比较value值,而不是Object的比较地址。
Integer在进行运算,跟int进行==比较时会进行自动拆箱,因此在for循环中进行叠加运算是不太合适的(频繁拆箱影响效率),应换为其它数据类型。
缓存部分看如下代码:
-----------------------------
关于缓存,看代码(jdk8):
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类中有一个IntegerCache静态内部类,这个类在初始化的时候构造了一个涵盖区间为-128-127的Integer数组,该数组为static final的。
Integer的valueOf()方法是将非Integer的数值转换为Integer:
valueOf的源码:
先判断给定的值是否在缓存区间,是直接返回缓存中的值,否则new一个新的。另外几个重载的valueOf()方法也是通过这个valueOf实现的。
Integer的自动装箱跟拆箱就是通过这个valueOf()来实现的,因此:
Integer a = 127;
Integer aa = 127;
Integer b = 128;
Integer bb = 128;
System.out.println(a == aa);//true
System.out.println(b == bb);//false
两者结果不同,原因是127在调用valueOf的时候发现在区间内会返回同一个对象,而超过127则new一个Integer,所以b跟bb是堆中的两个对象,一次为false。
需要注意的是跟int比较的时候Integer会自动拆箱为int:
int a = 128;
Integer aa = 128;
System.out.println(a == aa);//true
频繁拆箱造成性能损耗的例子:
Integer sum = 0;
for(int i=1000; i<5000; i++){
sum+=i;
}