Compare two Integer: why is == true? [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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 != ctvrty);  } 

回答1:

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.



回答2:

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.



回答3:

The autoboxing feature creates a new instance for every object.

try this:

int treti = 128; int ctvrty = 128; 


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