3

这两个代码片段有什么区别?

片段1:

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

片段 2:

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

4 回答 4

8

容忍空值

唯一的区别是,如果 o 为 null,则Objects.hashCode(o)返回 0 而o.hashCode()抛出 a NullPointerException

于 2013-04-24T08:49:12.357 回答
4

这是如何Objects.hashCode()实现的:

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

如果onull则将Objects.hashCode(o);返回0,而o.hashCode()将抛出一个NullPointerException

于 2013-04-24T08:50:31.927 回答
2
java.util.Objects {
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
}

这是 o.hashCode() 的 NPE 安全替代方案。

其他没有区别。

于 2013-04-24T08:51:20.883 回答
0
Object o = new Object();
int i = Objects.hashCode(o);

它返回非空参数的哈希码,空参数返回 0。这种情况是Objecto.It 引用的。它不会抛出NullPointerException

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

Object返回所引用的 hashCode() o。如果onull,那么您将获得一个NullPointerException.

于 2013-04-24T08:51:36.420 回答