比较两个整数:为什么== true? [英] Compare two Integer: why is == true?

查看:102
本文介绍了比较两个整数:为什么== true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Wrapper class和== operator

当我比较Integer时与==我有一些问题,所以
你可以解释为什么第二次测试也成功吗?

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

}


推荐答案

使用时 == 要比较对象,您实际上是在比较引用。即两个断言都是真的原因是因为 prvni druhy 引用相同的对象 while treti ctvrty 没有。

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.

这是因为JVM 缓存 Integer 对象的范围是-128到127,并在自动装箱时重新使用缓存的对象。

This is because the JVM caches Integer objects in the range -128 to 127, and reuses cached objects when autoboxing the values.

除非你切换到 int ,否则你可以通过 prvni.intValue() 或改为使用 prvni.equals(...)

Unless you switch to int instead, you could go through prvni.intValue() or use prvni.equals(...) instead.

这篇关于比较两个整数:为什么== true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆