什么不是 2 Long 变量等于 == 运算符在 Java 中进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19485818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are not 2 Long variables equal with == operator to compare in Java?
提问by Brady Zhu
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:
当我尝试比较 2 个 Long 变量时,我遇到了一个非常奇怪的问题,它们总是显示 false,我可以通过在 Eclipse 中调试来确保它们具有相同的数值:
if (user.getId() == admin.getId()) {
return true; // Always enter here
} else {
return false;
}
Both of above 2 return values are object-type Long, which confused me. And to verify that I wrote a main method like this:
以上 2 个返回值都是对象类型 Long,这让我很困惑。并验证我是否编写了这样的主要方法:
Long id1 = 123L;
Long id2 = 123L;
System.out.println(id1 == id2);
It prints true.
它打印为真。
So can somebody give me ideas?. I've been working in Java Development for 3 years but cannot explain this case.
所以有人可以给我一些想法吗?我在 Java 开发领域工作了 3 年,但无法解释这种情况。
采纳答案by BlackJoker
==
compares references, .equals()
compares values. These two Longs are objects, therefore object references are compared when using ==
operator.
==
比较引用,.equals()
比较值。这两个 Long 是对象,因此在使用==
运算符时比较对象引用。
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.
但是,请注意,Long id1 = 123L;
字面值123L
将使用 自动装箱到Long
对象中Long.valueOf(String)
,并且在内部,此过程将使用具有[-128,127]
范围的 LongCache ,而 123 在此范围内,这意味着长对象已被缓存,而这些两个实际上是相同的对象。
回答by Jigar Joshi
because ==
compares reference value, and smaller long values are cached
因为==
比较参考值,较小的长值被缓存
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
so it works for smaller long values
所以它适用于较小的长值
Also See
另见
回答by Thibault
Stuck on an issue for 4 hours because of the use of ==
... The comparison was ok on Long < 128
but ko on greater values.
由于使用==
...而被困在一个问题上 4 小时比较没问题,Long < 128
但 ko 值更大。
Generally it's not a good idea to use ==
to compare Objects
, use .equals()
as much as possible ! Keep ==, >, <, <= etc.
for primitives.
一般用==
比较不好Objects
,.equals()
尽量多用!保留==, >, <, <= etc.
原语。