**先上段代码
public class Test03 {
public static void main(String[] args) {
Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
System.out.println(f1 == f2);//返回true
System.out.println(f1.equals(f2));//返回true
System.out.println(f3 == f4);//返回false
System.out.println(f3.equals(f4));//返回true
}
}
***解释原因:
我们先要了解Integer自动封装int类型数据的底层代码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在Integer的代码中IntegerCache.low= - 128 ,IntegerCache.high = 127。当需要封装的数值不在-128~127之间时会new Integer。如果在范围内就直接返回Integer缓存中的对应数字。
要知道,**new出的两个对象地址不同;而返回的缓存中的数字地址相同。
**对于==比较的是两个对象的地址,而equals比较的是内容。
所以f1==f2返回true,而f3==f4返回false;
f1.equals(f2)返回true,f3.equals(f4)返回true;
探讨Java中Integer对象在-128到127范围内的缓存机制,及==与equals方法的区别。当数值在此范围内时,Integer对象直接从缓存中获取,超出范围则new对象。==比较对象地址,equals比较对象内容。
368

被折叠的 条评论
为什么被折叠?



