什么不是2长变量等于==运算符在Java中进行比较? [英] What are not 2 Long variables equal with == operator to compare in Java?

查看:105
本文介绍了什么不是2长变量等于==运算符在Java中进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试比较2个Long变量时,我遇到了一个非常奇怪的问题,它们总是显示为false,我可以通过Eclipse中的调试确定它们具有相同的数值:

I got a very strange problem when I'm trying to compare 2 Long variables, they always show false and I can be sure they have the same number value by debugging in Eclipse:

if (user.getId() == admin.getId()) {
    return true; // Always enter here
} else {
    return false;
}

以上两个返回值都是对象类型的Long,这让我很困惑。并验证我写了一个这样的主方法:

Both of above 2 return values are object-type Long, which confused me. And to verify that I wrote a main method like this:

Long id1 = 123L;
Long id2 = 123L;

System.out.println(id1 == id2);

它打印为真。

所以可以有人给我点子吗?我已经在Java Development工作了3年但是无法解释这个案例。

So can somebody give me ideas?. I've been working in Java Development for 3 years but cannot explain this case.

推荐答案

==比较参考,等于比较值。这两个Long是Object,所以他们比较引用。

== compares references,equals compares value. This two Long is Object so they compare references.

但是 Long id1 = 123L; 将自动自动装箱到在内部使用 Long.valueOf(String)的长对象,进程将使用LongCache,
和123之间的LongCache [-128,127]所以实际上是相同的对象。

BUT Long id1 = 123L; will auto be autoboxed to a Long object using Long.valueOf(String) internally,the process will use a LongCache, and 123 is between the LongCache[-128,127] so the are actually the same object.

这篇关于什么不是2长变量等于==运算符在Java中进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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