如何实现Java的哈希表? [英] How does Java implement hash tables?

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

问题描述

有谁知道java如何实现它的哈希表(HashSet的或HashMap的)?考虑到不同类型,一个可以把它放到一个哈希表的对象,似乎很难拿出一个哈希函数,将工作以及适用于所有情况。

Does anyone know how Java implements its hash tables (HashSet or HashMap)? Given the various types of objects that one may want to put in a hash table, it seems very difficult to come up with a hash function that would work well for all cases.

推荐答案

HashMap和HashSet的非常相似。事实上,第二个包含第一的一个实例。

HashMap and HashSet are very similar. In fact, the second contains an instance of the first.

一个HashMap中包含以遏制其条目桶的数组。数组大小始终是2的幂。如果你没有指定其他值,最初有 16 桶。

A HashMap contains an array of buckets in order to contain its entries. Array size is always powers of 2. If you don't specify another value, initially there are 16 buckets.

当你把一个条目,它(key和value),它决定在那里的条目将被插入了关键的哈希值code计算它的桶(散code不是它的内存地址和散列不是模量)。不同的条目可以在同一桶碰撞,因此它们会被放置在列表中。

When you put an entry (key and value) in it, it decides the bucket where the entry will be inserted calculating it from its key's hashcode (hashcode is not its memory address, and the the hash is not a modulus). Different entries can collide in the same bucket, so they'll be put in a list.

参赛作品将被插入,直到他们达到了客座率。这个因素是 0.75 默认情况下,不建议去改变它,如果你不是很确定你在做什么。 0.75为负载系数意味着 16 桶只能包含 12 输入一个HashMap( 16 * 0.75 )。然后,水桶阵列将被创建,的previous规模扩大一倍。所有参赛作品将再次在新的阵列把。这个过程被称为老调重弹,然后可能是昂贵的。

Entries will be inserted until they reach the load factor. This factor is 0.75 by default, and is not recommended to change it if you are not very sure of what you're doing. 0.75 as load factor means that a HashMap of 16 buckets can only contain 12 entries (16*0.75). Then, an array of buckets will be created, doubling the size of the previous. All entries will be put again in the new array. This process is known as rehashing, and can be expensive.

因此​​,最佳做法是,如果你知道有多少项目会被插入,是构造一个HashMap指定其最终大小:

Therefore, a best practice, if you know how many entries will be inserted, is to construct a HashMap specifying its final size:

new HashMap(finalSize);

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

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