what must be hashcode of null objects in Java?

后端 未结 4 1397
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 23:14

According to a comment from this post, hascode of null objects can throw NPE or a value of zero. This is implementation speci

4条回答
  •  -上瘾入骨i
    2021-02-20 00:02

    How would you calculate hashCode of an object that doesn't even exists? When p2 is null, invoking any method on it will throw a NPE. That isn't giving you any particular value of a hashCode.

    Objects.hashCode() is just a wrapper method, which performs a pre-check for null values, and for reference that is not null, it returns the same value as p2.hashCode() as in this case. Here's the source code of the method:

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

提交回复
热议问题