what must be hashcode of null objects in Java?

后端 未结 4 1394
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  深忆病人
    2021-02-20 00:09

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

    That is not true. (And it is not what @Bohemian's comment is saying!)

    What happens in HashMap and HashSet is that they treat null as a special case. Instead of calling hashcode() on the null object (which would NPE!!), they use zero in as a hard-coded alternative hashcode.

    I stress ... this is special case behaviour of HashMap and HashSet ... not hashcode().

    As your example shows, if you do attempt to call the hashcode() method on null, you will get an NPE. The JLS says that that is what will happen ... and it happens whenever you try to invoke any instance method on null.

    (On the other hand, the Objects.hashCode(obj) method does deal with the case where obj is null as a special case. And that's the whole point of the static method!)

提交回复
热议问题