StackOverFlow中对equals()的使用提出了几个需要注意的地方:
equals will only compare what it is written to compare, no more, no less.
equals方法只会实现方法中所写的比较逻辑。
if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
如果没有重写equals(),默认使用该类最近且重写了equals()的父类方法。需通过api查阅该父类equals()的实现逻辑,如果不符合你想要实现的,要重写equals()和hashCode()两个方法。
If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
如果没有父类重写equals(),则默认使用Objec类的equals()。通过API可知Object类的equals()实现逻辑与==一样。
Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.
重写equals()的同时需重写hashCode(),查阅API可知,如果equals()返回true时,两个对象的hashCode也应该相等,否则不能保证结果完全正确。