java编写一个完美的equals方法:
(1)显示参数命名为otherObject,稍后需要将它转换成另一个other的变量。
(2)检测this与otherObject是否引用同一个对象:
if(this==otherObjet) return true;
(3)检测otherObject是否为null,如果为null,返回false.
if(otherObject==null) return false;
(4)比较this与otherObject是否为同一个类。
if(getClass()!=otherObject.getClass()) return false;
如果所有的子类都拥有统一的语义,就使用instanceof检测。
(5)将otherObject转换为相应的类类型变量:
ClassName other = (ClassName)otherObject
(6)使用==比较基本类型域,使用equals比较对象域。如果所有的域都匹配,就返回true;否则返回false。
return field1 == other.fields && Objects.equals(fields,other.fileds) && ...;
如果在子类中重新定义equals,就要在其中包含super.equals(other)。