Why is it not recommended to use equals to judge whether objects are equal?


In this article, we will summarize the difference from A. equals (b), and then make a small analysis of the source code.

1、 When the value is null:

1.a.equals(b), a is null, and a nullpointexception exception is thrown.

2.a.equals(b), a is not null, B is null, and false is returned

3.Objects.equals(a, b)During comparison, if both a and B are null, return true; if one of a and B is null and the other is not null, return false. Note: no null pointer exception will be thrown.

Null. Equals ("ABC") → throw NullPointerException

"Objects. ABC" → null

2、 When the value is an empty string:

1. If both a and B are null string: “, thena.equals(b), the returned value is true. If one of a and B is not a null string, false is returned;

2. In this caseObjects.equalsConsistent with case 1 behavior.

"ABC". Equals ("") → return false

Objects. Equals ("ABC", "") → return false

3、 Source code analysis

1. Source code

//java www.fhadmin.cn
public final class Objects {
    private Objects() {
        throw new AssertionError("No java.util.Objects instances for you!");

     * Returns {@code true} if the arguments are equal to each other
     * and {@code false} otherwise.
     * Consequently, if both arguments are {@code null}, {@code true}
     * is returned and if exactly one argument is {@code null}, {@code
     * false} is returned.  Otherwise, equality is determined by using
     * the {@link Object#equals equals} method of the first
     * argument.
     * @param a an object
     * @param b an object to be compared with {@code a} for equality
     * @return {@code true} if the arguments are equal to each other
     * and {@code false} otherwise
     * @see Object#equals(Object)
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));

2. Description

First, the object address is judged. If it is true, the judgment will not be continued.

If it is not equal, the following expression means to judge that a is not null, and then according to the above knowledge points, there will be no null pointer.

Therefore, if they are all null, they will be true in the first judgment. If it is not empty and the address is different, it is important to judge A. equals (b).

4、 What’s the difference between “a = = B” and “A. equals (b)”?

If both a and B are objects, a = = B is a reference to compare the two objects. True will be returned only when a and B point to the same object in the heap.

A. equals (b) performs logical comparison. When the contents are the same, it returns true. Therefore, it is usually necessary to rewrite this method to provide logical consistency comparison.

This work adoptsCC agreement, reprint must indicate the author and the link to this article