- 检测this与otherObject是否引用同一个对象(做为优化语句)
if(this==otherObject) return true;
- 检测otherObject是否为null,如果为null,返回false
if(otherObject==null) return false;
- 比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass()检测。
if(getClass()!=otherObject.getClass()) return false;
如果所有子类都拥有统一的语义,就使用instanceof检测
if(!(otherObject instanceof ClassName)) return false;
- 将otherObject转换为相应的类类型变量
ClassName other = (ClassName) otherOject片
- 现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。若所有域都匹配,则返回true。
return field1 == other.field1&&Objects.equals(field2,other.field2)&&···;
如果子类中重新定义equals,就要在其中包含调用super.equals(other)。
super.equals(other)
java类对象进行equals比较的方法
最新推荐文章于 2024-04-23 22:01:41 发布