默认情况下,空对象的哈希码

huangapple go评论71阅读模式
英文:

Default hashCode for null object

问题

在Java中,Objects.hash(null)返回0

但是

Map<Integer, Integer> map = null;
Objects.hash(map)

将返回31。

英文:

In Java, Objects.hash(null) return 0

but

Map&lt;Integer, Integer&gt; map = null;
Objects.hash(map)

will return 31

答案1

得分: 2

与可变参数的解释方式有关。在底层,可变参数是通过创建一个数组来实现的。

Objects.hash(null) 的情况下,你显然传递了一个 null。这里没有数组。当你执行 Objects.hash(map) 时,这会转换为一个长度为1的数组,第一个也是唯一的元素是 null。

由于计算哈希码的方式,null 和一个具有1个null元素的数组具有不同的哈希码。

英文:

It is related to how varargs are interpretted. Under the hood, varargs parameters are implemented by creating an array.

In the Objects.hash(null) case, you are passing obviously literally passing null. There is no array. When you do Objects.hash(map), this is converted to an array of length 1, with null as the first and only element.

Because of the way that hash code is calculated, null and an array with 1 null element get different hash codes.

huangapple
  • 本文由 发表于 2020年4月7日 01:57:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61065969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定