Java wrapper classes object equality - odd behaviour [duplicate]

♀尐吖头ヾ 提交于 2019-12-12 11:49:52

问题


Possible Duplicate:
Wrapper class and == operator

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");

produces the following output:

smaller than byte

same

larger than byte 

not same

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).

Note: Same output on other HotSpot builds under linux Can anyone explain it?


Small edit, just to make it slightly more interesting:

Adding

if (i3 <= i4 && i3 >= i4) System.out.println("same after all...");

in the end, prints "same after all...".


回答1:


That's correct. The JVM will "cache" and reuse Integer instances when autoboxing small values.

See Java Language Specification Section 5.1.7 Boxing Conversion:

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.

When comparing Integers using <, >, <= and >= the values are un-boxed as opposed to != and ==.




回答2:


Integers between -127 and 127 are 'cached', so they return same reference, which means i1 and i2 point to same object.



来源:https://stackoverflow.com/questions/6911419/java-wrapper-classes-object-equality-odd-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!