举例说明
Integer num1 =100;
Integer num2 =100;
System.out.println(num1num2);
Integer num3 =200;
Integer num4 =200;
System.out.println(num3num4);
输出:true false
原因:因为自动装箱,会执行:
Integer num2 =Integer.valueOf(100);
valueOf里边有一段代码为:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
查看low里边的代码:
static final int low = -128;
static final int high;
static final Integer cache[];
low为-128;
由此可知cache数组里存的是-128 ~ 127,因此,当num1=num2=100时,返回的是100的存放地址,是一样的,返回true;而当num3=num4=200时,最大127,超出了范围,会执行return new Integer(i);这一行代码,开辟新的空间,因此指向地址是不一样的,返回false。
128陷阱
最新推荐文章于 2024-07-19 17:37:28 发布