【发布时间】:2018-01-31 14:45:44
【问题描述】:
我最近发现了Objects.hash() 方法。
我的第一个想法是,这大大整理了您的 hashCode() 实现。请参阅以下示例:
@Override
//traditional
public int hashCode() {
int hash = 5;
hash = 67 * hash + (int)(this.id ^ (this.id >>> 32));
hash = 67 * hash + (int)(this.timestamp ^ (this.timestamp >>> 32));
hash = 67 * hash + Objects.hashCode(this.severity);
hash = 67 * hash + Objects.hashCode(this.thread);
hash = 67 * hash + Objects.hashCode(this.classPath);
hash = 67 * hash + Objects.hashCode(this.message);
return hash;
}
@Override
//lazy
public int hashCode() {
return Objects.hash(id, timestamp, severity, thread, classPath, message);
}
虽然我不得不说这似乎好得令人难以置信。我也从未见过这种用法。
与实现自己的哈希码相比,使用Objects.hash() 有什么缺点吗?我什么时候会选择这些方法?
更新
尽管此主题已标记为已解决,但请随时发布提供新信息和疑虑的答案。
【问题讨论】:
-
另见
HashCodeBulider:commons.apache.org/proper/commons-lang/apidocs/org/apache/… -
但是公共构建器使用反射。它很方便,但绝对是性能杀手。
-
@NPE 我真的很想把它留给当地人。我不是整个外部 apache 常见的东西的忠实粉丝
-
使用 Lombok 和
@EqualsAndHashCode。 -
@MartinSchröder 谢谢,但我想保持我的依赖关系干净。