Java包装器类对象相等-奇怪的行为 [英] Java wrapper classes object equality - odd behaviour
问题描述
可能重复:
包装器类和==运算符
似乎对象相等包装器类的运算符会根据包装值是否在字节范围内而产生不同的结果。下面是演示此行为的代码段:
It seems as if object equality operator for wrapper classes produces different results depending on whether the wrapped value is in byte range or not. Here is a code snippet to demonstrate this behavior:
System.out.println("smaller than byte");
Integer i1 = 1;
Integer i2 = 1;
if (i1 == i2) System.out.println("same");
if (i1 != i2) System.out.println("not same");
System.out.println("larger than byte");
Integer i3 = 128;
Integer i4 = 128;
if (i3 == i4) System.out.println("same");
if (i3 != i4) System.out.println("not same");
产生以下输出:
smaller than byte
same
larger than byte
not same
注意:我在Linux的HotSpot(版本1.6.0_24-b07)上获得了此输出。对于Long和Short可能也会发生同样的情况(虽然尚未进行测试)。
Note: I got this output on HotSpot (build 1.6.0_24-b07) on linux. Same happens for Long and probably Short (haven't tested it though).
注意:在Linux
下的其他HotSpot构建中,输出相同。
Note: Same output on other HotSpot builds under linux Can anyone explain it?
小的编辑,只是使其变得更加有趣:
Small edit, just to make it slightly more interesting:
添加
if (i3 <= i4 && i3 >= i4) System.out.println("same after all...");
最后,打印 毕竟... c $ c>。
in the end, prints "same after all...
".
推荐答案
是正确的。自动装小值时,JVM将缓存并重用 Integer
实例。
That's correct. The JVM will "cache" and reuse Integer
instances when autoboxing small values.
请参见Java语言规范第5.1.7节装箱转换:
See Java Language Specification Section 5.1.7 Boxing Conversion:
如果装箱的p值为
true
,false
,一个字节,\u0000
到\u007f
范围内的字符strong>或-128到127 之间的整数或短数,则令r1和r2为p的任何两次装箱转换的结果。经常会出现r1 == r2的情况。
If the value p being boxed is
true
,false
, a byte, a char in the range\u0000
to\u007f
, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
比较 Integer
使用<
,>
,< =
和> =
的值未装箱,而不是!=
和 ==
。
When comparing Integer
s using <
, >
, <=
and >=
the values are un-boxed as opposed to !=
and ==
.
这篇关于Java包装器类对象相等-奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!