Integer aa = -128;
Integer bb = -128;
System.out.println(aa==bb);//true
Long aal = 127l;
Long bbl = 127l;
System.out.println(aal==bbl);//true
Double aad = 127d;
Double bbd = 127d;
System.out.println(aad==bbd);//false
Integer是对象,不应该true啊;原理是这样的:jvm会把-128-127整型缓存在方法区常量池中,当我们用127时,其实是引用到常量池中的127,也就是aa和bb的引用是同一个引用,所以为true.
Integer、Long的源码也可以看出:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
以上明白了吧;Double看他的源码,直接new 对象的。
public static Double valueOf(double d) {
return new Double(d);
}