比较两个整数:为什么 == 为 true?
可能的重复:
包装类和 == 运算符
嗨,当我将 Integer 与 == 进行比较时,我遇到了一些问题,所以 你能解释一下为什么第二次测试也成功吗?
@Test
public void integerTest() {
Integer prvni = 127;
Integer druhy = 127;
Integer treti = 128;
Integer ctvrty = 128;
assertTrue(prvni == druhy);
assertTrue(treti != ctvrty);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当使用
==
比较对象时,您实际上是在比较引用。即,两个断言都为 true 的原因是因为prvni
和druhy
引用同一个对象,而treti
和ctvrty
没有。这是因为 JVM 缓存
Integer
范围为 -128 到 127 的对象,并在自动装箱值时重用缓存的对象。除非您切换到 int ,否则您可以通过
prvni.intValue()
或使用prvni.equals(...)
代替。When using
==
to compare Objects, you're actually comparing the references. I.e., the reason both assertions are true is because theprvni
anddruhy
refer to the same object whiletreti
andctvrty
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 throughprvni.intValue()
or useprvni.equals(...)
instead.从 Java 1.5 开始,一些包装类引入了缓存。对于
Integer
,-128 到 127 之间的任何数字(包含 -128 和 127)都会落入缓存中。其他值每次都需要包装在一个新的 Integer 中。==
运算符比较引用。由于 127 的缓存 Integer 值实际上是同一个对象,因此==
返回true
。对于 128 个 Integer 对象,它们是两个不同的对象,并且不具有相同的引用相等性。有两种更可靠的方法可以比较相等性:
或者:
后一种比较利用了
Integer
实现Comparable
接口并因此定义compareTo 的事实
方法,如果第一个对象“小于”第二个对象,则返回负值;如果第一个对象“大于”第二个对象,则返回正值;如果对象比较相等,则返回零。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 anew Integer
every time.The
==
operator compares references. Since the cached Integer values for 127 are in fact the very same object,==
returnstrue
. For the 128Integer
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:
or:
The latter comparison takes advantage of the fact that
Integer
implements theComparable
interface and thus defines acompareTo
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: