Determining whether two Long objects are equal in Java

  • 2021-10-25 06:45:41
  • OfStack

Throw a question:


Long a = 4l;
Long b = 4l;
a == b //true

Long a = 128l;
Long b = 128l;
a == b //false

If the value of Long is between [-127, 128], it is no problem to judge whether it is equal with "= =". If it is not in this interval, it cannot be used with "= =" because of the following source code explanation:


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 it is not between [-127,128], there will be new1 new objects, naturally "= =" two different objects, and the result must be false.

Solution:

1. Conversion using longValue () in Long

Long a = 128l;
Long b = 128l;
a.longValue() == b.longValue() //true
2. Use equals () in Long

Long a = 128l;
Long b = 128l;
a.equals(b);//true

The following is the source code of this method:


public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

Pits in Comparison of Two Long Types

1 Generally speaking, two basic data types are compared with "= =", and Long types are rarely used for comparison.

However, when writing a project recently, I encountered two Long type comparisons, which were also directly used at that time. However, when debug, I found that the code did not enter the judgment body when executing the comparison judgment of these two Long types, and then searched for related problems on the Internet. In fact, it is very simple, but it is very easy to into the pit if I don't know it.

The solution is as follows:

You can make two variables of type Long call the = = longValue () = = method respectively.

Code:


Long a=...;
Long b=...;
if (a.longValue() == b.longValue()) {
             ...;
}

In fact, Long is a kind of java data packaging class, and the above belongs to the situation that packaging class Long is converted into basic data type long. The following lists other data packaging classes that are unpacked and converted into basic data types:

To convert Integer to int, you need to call the intValue () method

To convert Double to double, you need to call the doubleValue () method

To convert Float to float, you need to call the floatValue () method

Summary:

When a wrapper class Xxx is converted to the corresponding base data type, the xxxValue () method is called.


Related articles: