3

What's the difference between these two code snippets?

Snippet 1:

Object o = new Object();
int i = Objects.hashCode(o);

Snippet 2:

Object o = new Object();
int i = o.hashCode();
1
  • java.util.Objects since 1.7. Commented Apr 24, 2013 at 8:52

4 Answers 4

8

Tolerates null value

The only difference is that if o is null, Objects.hashCode(o) returns 0 whereas o.hashCode() would throw a NullPointerException.

Sign up to request clarification or add additional context in comments.

4 Comments

Objects is a class with hashCode being a static method in it.
@Apurv See here (since 1.7).
@ArjunRao: So, assuming there are no null objects, they're just the same?
No since Objects.hashCode(o) has an additional logic to determine if o is null. If you're sure o is not null, it is marginally (negligibly) better to use o.hashCode().
4

This is how Objects.hashCode() is implemented:

public static int hashCode(Object o) {
    return o != null ? o.hashCode() : 0;
}

If o is null then Objects.hashCode(o); will return 0, whereas o.hashCode() will throw a NullPointerException.

Comments

2
java.util.Objects {
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
}

This is a NPE safe alternative to o.hashCode().

No difference otherwise.

Comments

0
Object o = new Object();
int i = Objects.hashCode(o);

It returns the hash code of a not-null argument and 0 for null argument. This case it is Object referred by o.It doesn't throw NullPointerException.

Object o = new Object();
int i = o.hashCode();

Returns the hashCode() of Object referred by o. If o is null , then you will get a NullPointerException.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.