java - 如何避免 Object.equals 方法的多个 if else 块?
问题描述
我正在尝试实现这一点:
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;
其中'list'是一个类变量以及对象'o'的一个字段。请注意,对象“o”还有许多其他字段,包括布尔值和集合,我需要比较所有这些字段。我尝试查找相关答案,但其中大多数都推荐与我的场景无关的 switch case 或其他 Java 8 组件。
解决方案
你让事情变得非常复杂。写“等于”是冗长乏味的样板,但你让它变得更长。
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。
推荐阅读
- react-native - 安装 react-native-splash-screen 后 react-native android 应用程序崩溃
- python - Sybase Python ODBC
- c++ - 删除 cmake 中的预处理器定义
- php - 如何保护我网站上的重定向网址并阻止外部网站对它的不当使用?
- reactjs - 测试对 redux-saga 函数的调用
- html - 错误解析模板中的角度分页器错误
- python - 如何计算循环数据框中满足条件的值?
- android - 为华为应用程序库实现评价我们和更多应用程序链接
- gradle - 错误:无法在 Jar 中找到或加载主类
- javascript - node js require() 和 Rhino Shell load() 有什么区别?