Why are 2 Long variables not equal with == operator in Java?

前端 未结 3 1216
借酒劲吻你
借酒劲吻你 2020-12-17 09:05

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:<

3条回答
  •  一向
    一向 (楼主)
    2020-12-17 09:41

    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?

提交回复
热议问题