java类对象进行equals比较的方法

来源:互联网 发布:图片无缝拼接软件 编辑:程序博客网 时间:2024/06/14 21:42
  1. 检测this与otherObject是否引用同一个对象(做为优化语句)
    if(this==otherObject) return true;
  2. 检测otherObject是否为null,如果为null,返回false
    if(otherObject==null) return false;
  3. 比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass()检测。
    if(getClass()!=otherObject.getClass()) return false;
    如果所有子类都拥有统一的语义,就使用instanceof检测
    if(!(otherObject instanceof ClassName)) return false;
  4. 将otherObject转换为相应的类类型变量
    ClassName other = (ClassName) otherOject片
  5. 现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。若所有域都匹配,则返回true。
    return field1 == other.field1&&Objects.equals(field2,other.field2)&&···;
    如果子类中重新定义equals,就要在其中包含调用super.equals(other)。
    super.equals(other)
0 0
原创粉丝点击