我正在尝试实现这一点:
public boolean equals(Object o) {
if (o == this) {
return true;
}
if ((null == o) || !(o instanceof Document)) {
return false;
}
Document other = (Document) o;
// compare in a null-safe manner
if (list == null) {
if (other.list != null)
return false;
} else if (other.list == null)
return false;
else if (!(list.size() == other.list.size())
&& !(list.equals(other.list)))
return false;
return true;
其中“列表”是类变量,也是对象“ o”的字段。请注意,对象“ o”还有许多其他字段,包括布尔值和集合,我需要将它们全部进行比较。我试图找到相关的答案,但是大多数建议使用开关盒或其他与我的场景无关的Java 8组件。
直接重写将是:
// compare in a null-safe manner
if (list == null || other.list == null) {
return list == other.list;
} else {
return list.size() == other.list.size() ||
list.equals(other.list));
}
[除非list
的类型是标准Java SE List
类,否则您可以取消size()
微观优化。 (典型的`List.equals实现将为您完成此操作。)因此,我们可以将以上内容重写为
// compare in a null-safe manner
if (list == null || other.list == null) {
return list == other.list;
} else {
return list.equals(other.list));
}
除了Objects.equals(...)
就是这样做的。因此,最后的重写是:
// compare in a null-safe manner
return Objects.equals(list, other.list);
尚不清楚IDE是否会生成equals
方法以null安全的方式测试这些字段。但是,与此相反的是,建议您设计类,这样就不必这样做了。例如,使用空的List
而不是null
。
您使事情变得非常复杂。写“等于”是冗长而乏味的样板,但您要使其更长。
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Document)) {
return false;
}
Document other = (Document) o;
if (!Objects.equals(list, other.list)) {
return false;
}
return true;
}
每个参考字段所需的全部就是上面的三行,对于基元也是如此(别忘了为浮点处理NaN)。>>
您的条件不仅更长,而且缺乏对称性。这使得编写起来更加困难,并且更容易出错。
无论如何,写“等于”不是您应该经常手动做的事情。我建议使用Lombok,并且还有更多工具,例如AutoValue或EqualsBuilder。