Objects.hash()vs Objects.hashCode(),需要澄清 [英] Objects.hash() vs Objects.hashCode(), clarification needed

查看:96
本文介绍了Objects.hash()vs Objects.hashCode(),需要澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 7中,我们拥有

in Java 7 we have

o.hashCode();
Objects.hashCode(o);

    Objects.hash(o);

前两个与空点检查大致相同,但是最后一个是什么?

The first 2 are roughly the same with the null point check, but what is last one?

提供单个对象引用时,返回值会 不等于该对象引用的哈希码.

When a single object reference is supplied, the returned value does not equal the hash code of that object reference.

那是为什么?我的意思是,我们理解不需要3个做相同事情的方法,但是为什么我们完全需要Objects.hash()?您什么时候选择使用一个对另一个?

Why is that? I mean, we don't need 3 methods that do the same thing, I understand that, but why do we need Objects.hash() at all? When would you chose to use one vs another?

推荐答案

请参阅

See the documentation for hashCode and hash. hash takes Object... while hashCode takes Object. The example given is:

@Override public int hashCode() {
    return Objects.hash(x, y, z);
}

  • Objects.hash(Object... values)应该用于需要散列对象序列的情况,例如定义自己的hashCode方法时,想要一个简单编码的哈希值来表示组成对象身份的多个值.
  • Objects.hashCode(Object o)应该用于单个对象的哈希,如果对象为null,则不抛出.
  • Object::hashCode()当您需要单个对象的哈希值时应使用,如果对象为null,则将引发异常.
    • Objects.hash(Object... values) should be used in cases when you want a hash of a sequence of objects, e.g. when defining your own hashCode method and want a simply-coded hash for multiple values that make up the identity of your object.
    • Objects.hashCode(Object o) should be used when you want the hash of a single object, without throwing if the object is null.
    • Object::hashCode() should be used when you want the hash of a single object, and will throw an exception if the object is null.
    • 请注意,hash(o)hashCode(o)不一定会返回相同的内容!如果对单个对象执行此操作,则可能应使用hashCode.

      Note that hash(o) and hashCode(o) won't necessarily return the same thing! If you're doing it for a single object, you should probably use hashCode.

      这篇关于Objects.hash()vs Objects.hashCode(),需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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