//在-128~127 之外的数
Integer i1 =200;
Integer i2 =200;
System.out.println("i1==i2: "+(i1==i2));
// 在-128~127 之内的数
Integer i3 =100;
Integer i4 =100;
System.out.println("i3==i4: "+(i3==i4));
结果为:false; true;
首先,i1,i2是Integer类的实例,因此“==”比较的是两个实例的内存地址。
因为整型的包装类存在常量池,一次性把从-128到127之间的所有数都初始化了.当你使用这些数的时候不是创建新对象而是直接从这个常量池里面取值.所以当你赋值100的时候是取的常量池里的100,因此两个对象内存地址一样.而赋值200的时候两个对象分别new对象,因此内存地址不同.
以下是Integer源代码的常量池实现:
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache(){}
}
转载地址
https://blog.csdn.net/xiao_20170620/article/details/73649190