自动装箱规范要求,boolean、byte、char<=127, -128<= short、int <=127被包装到固定的对象中。
Integer a = 1000;
Integer b = 1000;
if(a == b) {
System.out.println("相等");
}
a和b不在-128~127之间,所以不成立。
Integer a = 127;
Integer b = 127;
if(a == b) {
System.out.println("相等");
}
a和b都等于127,介于-128~127之间,所以他俩其实指向的是同一个对象,所以用==比较的话,输出相等。
以下是Integer.valueof()的源代码:
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);
}
简单地解释这段代码,就是如果传入的int在IntegerCache.low和IntegerCache.high之间,那就尝试看前面的缓存中有没有打过包的相同的值,如果有就直接返回,否则就创建一个Integer实例。IntegerCache.low 默认是-128;IntegerCache.high默认是127。
注:如果要比较两个对象的内容是否相同,尽量不使用== 或者!= 来比较,可以使用equal()来实现。
探讨了自动装箱规范中boolean、byte、char<=127,-128<=short、int<=127被包装到固定对象中的规则。深入分析Integer.valueOf()源代码,解释了当传入的int值在特定范围内,会从缓存中获取已存在的对象,而非创建新对象,以提升效率。
2912

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



