业务需要使用自定义的equals方法 已经shaixuan出4个字段
- 真的是不写不知道麻烦。
- equals 实现方式非常简单,只要对上述四个字段进行对比是否相同即可 只有String和Integer成员
- 使用euqals的时候需要先判断是否为空,否则有空指针异常
- 例如 每一个字段需要下面的判断流程 非常繁琐 ,可以直接使用Objects.euqals(o.getAppCode(),appcode)
if (o == this) { if (o != null && o.getAppCode().equals(appCode)) { } }
- 最后如下
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BusinessAppRelationDO)) { return false; } BusinessAppRelationDO o = (BusinessAppRelationDO) obj; return Objects.equals(o.getAppCode(),appCode) && Objects.equals(o.getCommonIsDel(), commonIsDel) && Objects.equals(o.getAccessAppCode(),accessAppCode) && StringUtils.equals(o.getPlatformType(),platformType); }
- 对于hashCode方法也需要重写 网上找到的一般教程均为
@Override public int hashCode() { int result = 17; result = result * 31 + appCode.hashCode(); result = result * 31 + accessAppCode.hashCode(); result = result * 31 + platformType.hashCode(); result = result * 31 + commonIsDel.hashCode(); return result; }
- 没有考虑到属性可能为null 修改为。 对于基本类型可以转换为包装类以后使用包装类的hashCode
@Override public int hashCode() { int result = 17; result = result * 31 + Objects.hash(appCode); result = result * 31 + Objects.hash(accessAppCode); result = result * 31 + Objects.hash(platformType); result = result * 31 + Objects.hash(commonIsDel); return result; }
- 后来发现已经提供了hash方法
@Override public int hashCode() { Objects.hash(appCode,accessAppCode,platformType,commonIsDel) }