public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
Integer c = 100;
Integer d = 100;
System.out.println("a == b is" + (a == b));
System.out.println("c == d is" + (c == d));
}
输出结果:
a == b is false
c == d is true
由于Java的自动装箱,a和b这两个引用变量,指向的不是同一个堆内存地址。而使用==比较时,默认是比较两者的内存地址是否相同,所以a和b用==来比较为false
但为什么c和d用==比较,结果却是true呢?在Java5中,在Interger的操作上引入了一个新功能来节省内存和提高性能。整型对象通过使用相同的对象引用实现了缓存和重用。
下面是java中java.util.Integer的部分源码:
static {
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);
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
}
}
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]
assert IntegerCache.high >= 127;
}
适用于整数值区间-128至127。只适用于自动装箱,并且使用构造函数创建对象不适合。

614

被折叠的 条评论
为什么被折叠?



