==, the difference between equals

The equals method in the Java language is actually handed over to the developer to overwrite, allowing the developer to define what conditions the two Objects are equal.

So we cannot simply say what equals compares. You want to know what the equals method of a class means is to look at the definition.



The default equals method in Java is implemented as follows:

public boolean equals(Object obj) {
    return (this == obj);
}


  The String class overrides this method. Intuitively, it compares whether the characters are all the same.


public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

How equals is compared is not important, but it is easy to step on the pit without understanding the purpose of equals.


Guess you like

Origin blog.csdn.net/a447332241/article/details/78953887
Recommended