这段程序的运行结果是什么?
public class Test {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
System.out.println(a == b);
Integer c = 128;
Integer d = 128;
System.out.println(c == d);
}
}
public class Test {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
System.out.println(a == b);
Integer c = 128;
Integer d = 128;
System.out.println(c == d);
}
}
当不再范围内的时候编译器不会自动的指向相同的地址,而是再开辟一个空间,虽然数值相同 但 地址不同 所以不相等.
当k属于-128~127之间,那么a=b 否则a!=b.
对于Character c1=new Character (k);Character c2=new Character (k)
当k字符代表的ASCII范围在127以内,那么c1=c2 否则不等.
对于浮点数如果范围在-128-127之间不能缓存,对于Boolean类型true false有此缓存一句话,只要用的多的就放在缓存中提高性能。
Class Integer中的代码private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
去看看JDK的源码就知道怎么回事了
true
false
- -!
false
127在范围内等同于两个int比,是相等的.
范围外的是两个对象比,肯定是不等的.