相等判断
关于 == 的运行结果,只要我们记住一条:他比较的是引用(地址) 就好了,按照这个来分析结果
当且仅当比较的两个引用指向同一对象才返回true
举例:
Integer ==
代码举例:
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
Integer e = new Integer(100);//这种最好直接换成 Integer e = 100;
Integer f = new Integer(100);
System.out.println(a == b);
System.out.println(c == d);
System.out.println(e == f);
运行结果
true
false
false
看看Integer 的源代码就知道了,其实就是Integer 把-127-128 之间的每个值都建立了一个对应的Integer 对象,类似一个缓存。由于Integer 是不可变类,因此这些缓存的Integer 对象可以安全的重复使用。
Integer i = XXX ,就是Integer i = Interger.valueOf(XXX), 首先判断XXX 是否在-127-127 之间,如果是直接return 已经存在的对象,否则就只能new 一个了。
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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) {
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);
}
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() {}
}