Java中的hashCode()用途 [英] hashCode() purpose in Java

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

问题描述

我读过一本书,其中hashCode()显示了一个内存区域,该区域有助于(例如HashSets)在内存中定位适当的对象.但是,如果我们不能直接用Java操作内存,那怎么可能呢?没有指针,除了它,还创建了对象并将其从一个地方移动到另一个地方,而开发人员对此一无所知.

I read in a book that hashCode() shows a memory area which helps (e.g. HashSets) to locate appropriate objects in memory. But how can that be true if we cannot manipulate memory in Java directly? There are no pointers, in addition to it objects are created and moved from one place to another and the developer doesn't know about it.

我读到像hashCode() {return 42;}这样的实现是可怕而可怕的,但是如果我们不能指示VM将对象放在哪里,有什么区别呢?

I read that realization like hashCode() {return 42;} is awful and terrible, but what's the difference if we can't instruct VM where to put our objects?

问题是:如果不能操作内存,hashCode()的目的是什么?

The question is: what is the purpose of hashCode() on deep level if we can't manipulate memory?

推荐答案

我喜欢 Jon Skeet的答案(+1)但是它需要知道哈希表如何工作.哈希表是一种数据结构,基本上是一个存储桶数组,它使用键的哈希码来确定将哪个存储桶粘贴到该条目中.这样,将来调用以检索该键上的所有内容时,就不必筛选整个对象.在哈希表中存储的事物列表中,哈希表可以计算密钥的哈希码,然后直接转到匹配的存储桶并查看.哈希码必须是可以快速计算的东西,您希望它是唯一的,但是如果不是,那不是一场灾难,除非在最坏的情况下(您的return 42;),这很糟糕,因为一切都会结束在同一个存储桶中,您将返回到所有内容进行筛选.

I like Jon Skeet's answer (+1) but it requires knowing how hash tables work. A hash table is a data structure, basically an array of buckets, that uses the hashcode of the key to decide which bucket to stick that entry in. That way future calls to retrieve whatever's at that key don't have to sift through the whole list of things stored in the hashtable, the hashtable can calculate the hashcode for the key, then go straight to the matching bucket and look there. The hashcode has to be something that can be calculated quickly, and you'd rather it was unique but if it isn't it's not a disaster, except in the worst case (your return 42;), which is bad because everything ends up in the same bucket and you're back to sifting through everything.

Object#hashCode的默认值可能基于诸如内存位置之类的东西,只是因为它是一个方便的随机数,但是由于对象在内存管理过程中被分流,因此该值被缓存了,无论如何也不会有人在意.由不同对象(例如String或BigDecimal)创建的哈希码当然与内存无关.这只是一个快速生成的数字,您希望它比以往更多时候是唯一的.

The default value for Object#hashCode may be based on something like a memory location just because it's a convenient sort-of-random number, but as the object is shunted around during memory management that value is cached and nobody cares anyway. The hashcodes created by different objects, like String or BigDecimal, certainly have nothing to do with memory. It's just a number that is quickly generated and that you hope is unique more often than not.

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

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