Determine whether two Long types are equal in Java

@see  https://blog.csdn.net/hxxanyifree/article/details/68063641

In the development, it is encountered whether the Long type comparison is equal, for example, Long A and Long B judge whether they are equal, and the habitual direct A==B at that time;


    There is indeed a problem with the self-test, but there is a problem with the test on the test side. At that time, I was depressed and then replaced it with A.equals(B) or A.longValue()==B.longValue() is correct;


    After fixing the bug, I feel that I need to see why. By looking at Long.class, we can see that

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

    If the value is between [-128, 127], it will be placed in the cache, and if it exceeds this range, a new object will be created, which means that == cannot determine whether the objects are equal. In the self-test, the A or B value is set to be relatively small, and the test will consider the effect of convenience, so it is GG.


Therefore, the Java foundation is very important. If you have nothing to do, you should look at the source code! ! ! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326465434&siteId=291194637