hashCode() 是如何在 Java 中实现的 [英] how is hashCode() implemented in Java

查看:24
本文介绍了hashCode() 是如何在 Java 中实现的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何hashCode() 实施了吗?

我的假设是它使用对象内存位置作为它运行散列函数的初始数字(种子).然而,事实并非如此.

My assumption is that it uses the object memory location as the initial number (the seed) on which it runs the hash function. However, this is not the case.

我还查看了 Hash:它在内部如何工作? 但它没有回答我的问题.

I've also looked at Hash : How does it work internally? but it does not answer my question.

是的,我可以下载 SDK,但在我下载并查看代码之前,也许其他人已经了解它.

Yes I could download the SDK, but before I do that and look at the code, perhaps someone else already has knowledge of it.

谢谢:)

我知道它应该被覆盖等等,所以请尽量保持主题:)

I know it should be overridden and such, so please try to stay on topic :)

推荐答案

当然它是特定于实现的,但通常对象的哈希码会被延迟计算并存储在对象头中.奇怪的事情是用标头来保持它们很小,同时允许复杂的锁定算法.

Of course it is implementation specific, but generally the hash code for an object will be computed lazily and stored in the object header. Odd things are done with headers to keep them small whilst allowing complex locking algorithms.

在 OpenJDK/Oracle JVM 中,计算初始哈希码的常用方法是基于第一次请求时的内存地址.对象在内存中移动,所以每次都使用地址不是一个好的选择.哈希码不是实际地址——通常是 8 的倍数,这对于在哈希表中直接使用不是很好,特别是在大小为 2 的幂的情况下.请注意,身份哈希码不是唯一的.

In the OpenJDK/Oracle JVM the usual method of computing the initial hash code is based on the memory address at the time of the first request. Objects move about in memory, so using the address each time would not be a good choice. The hash code isn't the actual address - that would typically be a multiple of eight which isn't great for using straight in a hash table particularly with a power of two size. Note identity hash codes are not unique.

HotSpot 具有构建时间选项,可始终使用零或使用安全随机数生成器 (SRNG) 进行测试.

HotSpot has build time options to always use zero or use a secure random number generator (SRNG) for testing purposes.

这篇关于hashCode() 是如何在 Java 中实现的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆