Guava与Apache Commons Hash/Equals构建器 [英] Guava Vs Apache Commons Hash/Equals builders
问题描述
我想知道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中有EqualsBuilder
和HashCodeBuilder
,而Guava中没有构建器.从Guava中获得的所有东西都是实用程序类MoreObjects
(由于现在在JDK中有这样的类,因此从Objects
重命名).
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).
番石榴方法的优点来自于建造者的不存在:
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.
Note also that there's also a ComparisonChain which is a sort of Comparable-builder.
这篇关于Guava与Apache Commons Hash/Equals构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!