Compare two Integer: why is == true? [duplicate]
Possible Duplicate:
Wrapper class and == operator
Hi when I am comparing Integer with == I have some problem so can you explain me why second test is success too ?
@Test
public void integerTest() {
Integer prvni = 127;
Integer druhy = 127;
Integer treti = 128;
Integer ctvrty = 128;
assertTrue(prvni == druhy);
assertTrue(treti != ctv开发者_Python百科rty);
}
When using ==
to compare Objects, you're actually comparing the references. I.e., the reason both assertions are true is because the prvni
and druhy
refer to the same object while treti
and ctvrty
does not.
This is because the JVM caches Integer
objects in the range -128 to 127, and reuses cached objects when autoboxing the values.
Unless you switch to int
instead, you could go through prvni.intValue()
or use prvni.equals(...)
instead.
Since Java 1.5, some of the wrapper classes have introduced a cache. For Integer
, any number between -128 and 127 inclusive fell in the cache. Other values needed to be wrapped in a new Integer
every time.
The ==
operator compares references. Since the cached Integer values for 127 are in fact the very same object, ==
returns true
. For the 128 Integer
objects, they are two different objects and do not have the same reference equality.
There are two more reliable ways you can compare for equality:
if (treti.equals(ctvrty)) { /* do something */ }
or:
if (treti.compareTo(ctvrty) == 0) { /* do something */ }
The latter comparison takes advantage of the fact that Integer
implements the Comparable
interface and thus defines a compareTo
method which returns a negative value if the first object is "less than" the second, a positive value if the first object is "greater than" the second, and zero if the objects compare equal.
The autoboxing feature creates a new instance for every object.
try this:
int treti = 128;
int ctvrty = 128;
精彩评论