使用Objects.hash()还是自己的hashCode()实现? [英] Use Objects.hash() or own hashCode() implementation?

查看:348
本文介绍了使用Objects.hash()还是自己的hashCode()实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了

I have recently discovered the Objects.hash() method.

我的第一个想法是,这可以使您的hashCode()实现更加整洁.请参见以下示例:

My first thought was, that this tidies up your hashCode() implementation a lot. See the following example:

@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);
}

尽管我不得不说这似乎太过真实了.而且我从未见过这种用法.

Although I have to say that this seems too good to be true. Also I've never seen this usage.

与实现自己的哈希码相比,使用Objects.hash()有什么缺点吗?我什么时候会选择每种方法?

Are there any downsides of using Objects.hash() compared to implementing your own hash code? When would I choose each of those approaches?

更新

尽管此主题已标记为已解决,但请随时发布可提供新信息和新问题的答案.

Although this topic is marked as resolved, feel free to keep posting answers that provide new information and concerns.

推荐答案

请注意,Objects.hash的参数为Object....这有两个主要结果:

Note that the parameter of Objects.hash is Object.... This has two main consequences:

  • 在哈希码计算中使用的原始值必须被装箱,例如this.idlong转换为Long.
  • 必须创建一个Object[]才能调用该方法.
  • Primitive values used in the hash code calculation have to be boxed, e.g. this.id is converted from long to Long.
  • An Object[] has to be created to invoke the method.

如果频繁调用hashCode,则可能会增加创建这些不必要"对象的成本.

The cost of creating of these "unnecessary" objects may add up if hashCode is called frequently.

这篇关于使用Objects.hash()还是自己的hashCode()实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆