Objects.hash() vs Objects.hashCode(), clarification needed

后端 未结 3 1245
孤城傲影
孤城傲影 2020-12-04 14:29

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

3条回答
  •  天涯浪人
    2020-12-04 14:44

    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) 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.

    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.

提交回复
热议问题