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

杀马特。学长 韩版系。学妹 提交于 2019-12-04 04:27:41

问题


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:


Tolerates null value

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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16187453/difference-between-objects-hashcode-and-new-object-hashcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!