我最近发现了 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()
有什么缺点吗?我什么时候会选择这些方法?
更新
尽管此主题已标记为已解决,但请随时发布提供新信息和疑虑的答案。
最佳答案
注意Objects.hash
的参数是Object...
。这有两个主要后果:
- 哈希码计算中使用的原始值必须装箱,例如
this.id
从long
转换为Long
。 - 必须创建一个
Object[]
来调用该方法。
如果经常调用 hashCode
,创建这些“不必要”对象的成本可能会增加。
关于java - 使用 Objects.hash() 还是自己的 hashCode() 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832458/