Java – implement the equals method using CompareTo

General question: when implementing the override of a default equals method in Java, how should the implemented CompareTo method be used to write independent logic to the equals method? I noticed that foo was mentioned in another question Equals ((string) null) returns false, while string CompareTo ((string) null) throws a NullPointerException Make these inconsistent results an ideal function?

Sample equal method:

@Override
public boolean equals(Object obj) {
    if (obj != null && obj instanceof MyClass) {
        MyClass msg = (MyClass)obj;
        return this.compareTo(msg) == 0;
    }
    return false;
}

Editing: references from comparable documents

Edit:

After further review, I found that the comparable file also states as follows:

Ergo, because null CompareTo (x) will obviously throw an NPE, and X. CompareTo (null) should also throw an NPE This is not the case for equality I am very interested in the correct handling of NPE, so I think this is more important

Solution

The difference between equals () and CompareTo () is that equals () only checks whether two objects are equal, and CompareTo () is used to identify the natural order of instances of the specified class Also, the equals () method has a contract with the hashcode () method, but CompareTo () does not

According to Javadoc:

You are free to reuse CompareTo () method logic in the equals () method, but remember all contracts with equals (), hashcode () and Javadoc for CompareTo () methods If they don't conflict with each other, go on

I think the execution of the contract is more important

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>