看到了一个比较坑的问题:integer == integer 返回 true 还是 false 呢?
所以你觉得下面两个输出是什么呢?(波浪线忽略,是因为封装类型不建议用“==”,应该是equals)
答案很简单,第一个 integer = 20, 返回的是 true,第二个 integer = 321 返回的是false !!!
what???
是因为,
一来:Integer里弄了一个缓存,对于在 -128—127 之间的数值,会直接使用该缓存里的对象 ;
所以也就是说 在我们比较 integer = 20 的时候,其实拿取的是同一个对象,所以会返回true。
二来:因为321超出了 -128~127这个区间,那么系统会重新生成新的对象,所以比较的时候就会拿取不同的对象做比较,因此就会返回false。
为甚呢?
对于Integer类java为了提高效率(integer在加载时就会调用Integer.valueOf()方法),初始化了-128–127之间的整数对象,因此Integer类取值-128–127的时候效率最高。
部分源码如下:
tatic {
// 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;
}
当然integer和int的取值范围还是一致的
取值范围是从-2147483648 至 2147483647(-231至 231-1) ,包括-2147483648 和 2147483647。