Guava 与 Apache Commons Hash/Equals 建设者

Guava Vs Apache Commons Hash/Equals builders

我想知道 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 中找到更多信息。如果有的话,了解更多差异(尤其是任何性能改进?)会很有用。

我将此差异称为 "existence"。 Apache Commons 中有 EqualsBuilderHashCodeBuilder,而 Guava 中没有构建器。你从 Guava 得到的只是一个实用程序 class MoreObjects(从 Objects 重命名,因为现在 JDK 中有这样一个 class)。

Guava 方法的优点来自构建器的不存在:

  • 它不产生垃圾
  • 速度更快

JIT 编译器可能会通过 Escape Analysis 消除垃圾以及相关的开销。然后他们变得同样快,因为他们做的完全一样。

我个人认为构建器的可读性稍微好一些。如果您发现它们不能更好地使用,那么 Guava 无疑是适合您的选择。如您所见,静态方法足以完成任务。

另请注意,还有一个 ComparisonChain,它是一种 Comparable-builder。

Guava 在底层使用 Arrays.hashCode()。 Varagrs 会带来性能损失,并且有可能进行自动装箱,这会再次影响性能。根据 Java 的 documentation

If the array contains other arrays as elements, the hash code is based on their identities rather than their contents

Objects.hasCode 的替代方案可能是 Objects.deepHashCode,但 Guava 并未使用它。在循环引用的情况下它有一个缺点

It is therefore unacceptable to invoke this method on an array that contains itself as an element

通常 Apache Commons 的工作方式更像 deepHashCode,但可能会增加反射并解决上述所有问题,但(可以说)可能会遭受更差的性能。

表单设计视角 Apache Commons 实施有效 Java 项目 10 和 11 制定的规则。这给它增添了一种非常不同的感觉