自动装箱规范要求,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()来实现。
最后
以上就是调皮蜗牛最近收集整理的关于自动装箱、128陷阱的全部内容,更多相关自动装箱、128陷阱内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复