Integer a = 127; // 将整形127装箱对象 Integer b = 127; // 同上 System.out.print( a==b ); // true System.out.print(a.equals(b)); true
Integer a = 127 实际为Integer a =Integer.valueOf(127);
Integer a = 128; Integer b = 128; System.out.print( a==b ); false System.out.print(a.equals(b)); true
127与128 == 运行结果不同的原因在于,当值为小于一个字节时不会再占用另外一个空间,也就是说第一个代码块中a与b占用的是同一块内存,所以为true,但是第二块代码中则不是
源码:
public
static
Integer valueOf(
int
i) {
if
(i >= -
128
&& i <= IntegerCache.high)
// 没有设置的话,IngegerCache.high 默认是127
return
IntegerCache.cache[i +
128
];
else
return
new
Integer(i);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。