Abh*_*hek 13 java apache-commons guava
我想知道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();
}
Run Code Online (Sandbox Code Playgroud)
番石榴:
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);
}
Run Code Online (Sandbox Code Playgroud)
hashCode:
Apache Commons:
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(field1)
.append(field2)
.toHashCode();
}
Run Code Online (Sandbox Code Playgroud)
番石榴:
public int hashCode() {
return Objects.hashCode(field1, field2);
}
Run Code Online (Sandbox Code Playgroud)
其中一个关键差异似乎是使用Guava版本提高了代码可读性.
我无法从https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained中找到更多信息.知道更多差异(特别是任何性能改进?)如果有的话会很有用.
maa*_*nus 21
我称这种差异为"存在".有EqualsBuilder和HashCodeBuilder在Apache的百科全书,并有番石榴没有建设者.你从Guava得到的只是一个实用程序类MoreObjects(现在改名Objects为JDK中的这样一个类).
番石榴方法的优点来自于构建者的不存在:
JIT编译器可以通过Escape Analysis消除垃圾以及相关的开销.然后他们同样快速地完成同样的事情.
我个人觉得建设者的可读性稍微高一些.如果您发现没有更好地使用它们,那么番石榴肯定是适合您的.如您所见,静态方法足以完成任务.
另请注意,还有一个ComparisonChain,它是一种Comparable-builder.
| 归档时间: |
|
| 查看次数: |
9533 次 |
| 最近记录: |