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

查看:429
本文介绍了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天全站免登陆