What are not 2 Long variables equal with == operator to compare in Java?

天涯浪子 提交于 2019-11-28 02:35:58

问题


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

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

It prints true.

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


回答1:


== compares references, .equals() compares values. These two Longs are objects, therefore object references are compared when using == operator.

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.




回答2:


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

  • Integer wrapper class and == operator - where is behavior specified?



回答3:


Stuck on an issue for 4 hours because of the use of == ... The comparison was ok on Long < 128 but ko on greater values.

Generally it's not a good idea to use == to compare Objects, use .equals() as much as possible ! Keep ==, >, <, <= etc. for primitives.



来源:https://stackoverflow.com/questions/19485818/what-are-not-2-long-variables-equal-with-operator-to-compare-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!