本文介绍了Guava 与 Apache Commons Hash/Equals 构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Guava 与 Apache Commons 在 equals 和 hashCode 构建器方面的主要区别是什么.

I was wondering what are key differences between Guava vs Apache Commons with respect to equals and hashCode builders.

等于:

Apache Commons:

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:

Apache Commons:

public int hashCode() {
    return new HashCodeBuilder(17, 37)
            .append(field1)
            .append(field2)
            .toHashCode();
}

番石榴:

public int hashCode() {
    return Objects.hashCode(field1, field2);
}

主要区别之一似乎是提高了 Guava 版本的代码可读性.

One of the key difference appears to be improved code readability with Guava's version.

我无法从 https://code.google 找到更多信息.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained.如果有的话,了解更多差异(尤其是任何性能改进?)会很有用.

I couldn't find more information from https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained. It would be useful to know more differences (especially any performance improvement?) if there are any.

推荐答案

我将这种差异称为存在".Apache Commons 中有 EqualsBuilderHashCodeBuilder,而 Guava 中没有构建器.您从 Guava 获得的只是一个实用程序类 MoreObjects(从 Objects 重命名,因为现在 JDK 中有这样一个类).

I'd call this difference "existence". There are EqualsBuilder and HashCodeBuilder in Apache Commons and there are no builders in Guava. All you get from Guava is a utility class MoreObjects (renamed from Objects as there's such a class in JDK now).

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

The advantages of Guava's approach come from the non-existence of the builder:

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

JIT 编译器可以通过转义分析以及相关的开销来消除垃圾.然后,它们的速度与完全相同的速度一样快.

The JIT compiler can possibly eliminate the garbage via Escape Analysis and also the associated overhead. Then they get equally fast as they do exactly the same.

我个人认为构建器更具可读性.如果您发现没有更好地使用它们,那么 Guava 对您来说肯定是正确的选择.如您所见,静态方法足以完成任务.

I personally find the builders slightly more readable. If you find not using them better, then Guava is surely the right thing for you. As you can see, the static methods are good enough for the task.

另请注意,还有一个 ComparisonChain 这是一种 Comparable-builder.

Note also that there's also a ComparisonChain which is a sort of Comparable-builder.

这篇关于Guava 与 Apache Commons Hash/Equals 构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:38