Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

java 7 - Objects.hash() vs Objects.hashCode(), clarification needed

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.

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 Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...