空对象的默认哈希码

问题描述 投票:1回答:1

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

但是

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

将返回31

java hashcode
1个回答
1
投票
Objects.hash(null)情况下,您显然传递的是字面上传递的null。没有数组。当您执行Objects.hash(map)时,它将转换为长度为1的数组,其中null为第一个也是唯一的元素。

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

© www.soinside.com 2019 - 2024. All rights reserved.