Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
share|improve this question
java.util.Objects since 1.7. – 卢声远 Shengyuan Lu Apr 24 at 8:52

4 Answers

up vote 7 down vote accepted

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

share|improve this answer
Objects is a class with hashCode being a static method in it. – Arjun Rao Apr 24 at 8:50
2  
@downvoter: Please explain. – Arjun Rao Apr 24 at 8:50
@Apurv See here (since 1.7). – Dukeling Apr 24 at 8:52
@ArjunRao: So, assuming there are no null objects, they're just the same? – MC Emperor Apr 24 at 9:13
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(). – Arjun Rao Apr 24 at 9:14
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.

share|improve this answer
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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.