HashMap 初始化参数(load/initialcapacity) [英] HashMap initialization parameters (load / initialcapacity)

查看:22
本文介绍了HashMap 初始化参数(load/initialcapacity)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该传递什么值来为 N 个项目创建一个高效的基于 HashMap/HashMap 的结构?

What values should I pass to create an efficient HashMap / HashMap based structures for N items?

ArrayList 中,有效数字是 N(N 已经假设未来增长).HashMap 的参数应该是什么?((int)(N * 0.75d), 0.75d)?更多的?较少的?改变负载因子有什么影响?

In an ArrayList, the efficient number is N (N already assumes future grow). What should be the parameters for a HashMap? ((int)(N * 0.75d), 0.75d)? More? Less? What is the effect of changing the load factor?

推荐答案

关于负载因子,我将简单引用 HashMap javadoc:

Regarding the load factor, I'll simply quote from the HashMap javadoc:

作为一般规则,默认负载因子 (.75) 在时间和空间成本之间提供了很好的权衡.较高的值会减少空间开销,但会增加查找成本(反映在 HashMap 类的大多数操作中,包括 get 和 put).设置初始容量时应考虑映射中的预期条目数及其负载因子,以尽量减少重新哈希操作的次数.如果初始容量大于最大条目数除以负载因子,则不会发生重新哈希操作.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

意思是,加载因子不应从 .75 更改,除非您要进行一些特定的优化.初始容量是您唯一想要更改的内容,并根据您的 N 值进行设置 - 意思是 (N/0.75) + 1 或该区域的某些内容.这将确保表总是足够大并且不会发生重新散列.

Meaning, the load factor should not be changed from .75 , unless you have some specific optimization you are going to do. Initial capacity is the only thing you want to change, and set it according to your N value - meaning (N / 0.75) + 1, or something in that area. This will ensure that the table will always be large enough and no rehashing will occur.

这篇关于HashMap 初始化参数(load/initialcapacity)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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