MC Emperor
MC Emperor

Reputation: 23027

Difference between Objects.hashCode() and new Object().hashCode()?

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();

Upvotes: 3

Views: 268

Answers (4)

Arjun Rao
Arjun Rao

Reputation: 677

Tolerates null value

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

Upvotes: 8

AllTooSir
AllTooSir

Reputation: 49412

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.

Upvotes: 0

Vitaly
Vitaly

Reputation: 2800

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.

Upvotes: 2

jlordo
jlordo

Reputation: 37833

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.

Upvotes: 4

Related Questions