我想知道Guava与Apache Commons在equals和hashCode builder方面的主要区别。
equals:
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上找不到更多信息。如果有的话,了解更多差异(特别是任何性能改进)会很有用。
AutoValue
的工具来生成值对象的equals
/hashCode
/toString
等方法。 - ColinD