笔试的时候遇到一个问题:
Integer i1 = 127;
Integer i2 = 127;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
System.out.println(i3==i4);
System.out.println(i3.equals(i4));
输出结果是true true false true
提到了==与equals的区别,第一反应是String。
String s = new String("....")是分配在堆中不同位置的,==返回false。
String s = "..."; String ss = "..." 指向池中同一个空间,然会true
equals比较的是对象的值,而==比较的是对象本体(位置)。
Integer也有区别?
附上java的源码:
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() {}
}
可以看出来 Integer 也有常量池 范围是 -128~127
所以在此范围内的 == 返回true,范围外的 范围false。(当然,equals全部返回true)
同样,Short Long 的常量池范围也是-128~127。
Boolean 也实现了常量池的功能。毕竟只有true和false两个值
Character的范围0~127