直接上代码:
System.out.println(Integer.valueOf(127) == Integer.valueOf(127));
System.out.println(Integer.valueOf("127") == Integer.valueOf("127"));
System.out.println(Integer.valueOf("128") == Integer.valueOf("128"));
System.out.println(Integer.parseInt("128") == Integer.valueOf("128"));
程序输出结果是:
true
false
false
true
为什么呢?
1.对于int值 -128<=i<=127,直接从缓存取
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);
}
2.显然,valueOf缓存的是int对象,对于字符串"127"每次解析都是重新生成一个对象,所以两者不等
public static Integer valueOf(String s) throws NumberFormatException
{
return new Integer(parseInt(s, 10));
}
3.同2
4.parseInt返回的是int值,不是对象,与Integer比较的时候当然相同
PS:Long对象也存在同样的现象。