【发布时间】:2015-09-12 12:46:48
【问题描述】:
我想知道 Guava 与 Apache Commons 在 equals 和 hashCode 构建器方面的主要区别是什么。
等于:
Apache Commons:
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { return false; }
MyClass other = (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, other.field1)
.append(field2, other.field2)
.isEquals();
}
番石榴:
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { return false; }
MyClass other = (MyClass) obj;
return Objects.equal(this.field1, other.field1)
&& Objects.equal(this.field1, other.field1);
}
哈希码:
Apache Commons:
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(field1)
.append(field2)
.toHashCode();
}
番石榴:
public int hashCode() {
return Objects.hashCode(field1, field2);
}
主要区别之一似乎是 Guava 版本提高了代码可读性。
我无法从https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained 找到更多信息。如果有任何差异,了解更多差异(尤其是任何性能改进?)会很有用。
【问题讨论】:
-
Apache 创建了一个临时对象,但从好的方面来说,它还支持反射式构建快速原型代码。
-
正确。谢谢,本。
-
还可以考虑像
AutoValue这样的值对象来为您生成equals/hashCode/toString等。 -
相关:Java 7 包括 Objects.equals 和 Objects.hash,它们的工作方式与 Guava 类似
-
尽管具有所有可读性,OP 的作者仍然犯了一个错误,将 field1 比较两次并忘记了 field2(番石榴等于)。通过简单的实现,静态代码分析器会发出警报......
标签: java guava apache-commons