为什么Java中2个Long变量与==运算符不相等? [英] Why are 2 Long variables not equal with == operator in 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开发已经3年了,但是无法解释这种情况。
So can somebody give me ideas?. I've been working in Java Development for 3 years but cannot explain this case.
推荐答案
==
比较引用。 equals()
比较值。这两个Long是对象,因此使用 ==
运算符时会比较对象引用。
==
compares references, .equals()
compares values. These two Longs are objects, therefore object references are compared when using ==
operator.
但是,请注意 Long id1 = 123L;
文字值 123L
将自动装箱为 Long
对象使用 Long.valueOf(String)
,并且在内部,此过程将使用LongCache,该LongCache具有 [-128,127]
范围,而123在此范围内,这意味着将缓存长对象,而这两个实际上是相同的对象。
However, note that in Long id1 = 123L;
literal value 123L
will be auto-boxed into a Long
object using Long.valueOf(String)
, and internally, this process will use a LongCache which has a [-128,127]
range, and 123 is in this range, which means, that the long object is cached, and these two are actually the same objects.
这篇关于为什么Java中2个Long变量与==运算符不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!