What are not 2 Long variables equal with == operat

2019-01-26 04:41发布

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.

3条回答
家丑人穷心不美
2楼-- · 2019-01-26 05:14

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

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.

查看更多
贪生不怕死
3楼-- · 2019-01-26 05:34

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-26 05:37

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

查看更多
登录 后发表回答