java - 哪个是 HashMap 的更好选择?

标签 java hashmap

哪个是更好的选择:

为什么?

还有HashMap属性中的loadfactormodcount是什么?

当我在 eclipse 中调试我的代码并查看 HashMap 的值时,它显示一个名为 loadfactor 的属性,值为 0.75 和一个名为 modcount< 的属性 值为 3。


我在代码中使用 hashmap 的地方:-

我正在开发一个通讯应用程序,您可以说是一个聊天应用程序。其中我将所有发送/接收的消息存储在 HashMap 中。现在,由于我无法假设用户将发送/接收多少消息,因此我声明了一个没有初始容量的 HashMap 。我写的是

Map<String, Map<String, List<String>>> usersMessagesMap = new HashMap<String, Map<String,List<String>>>();

如果我以 100 或更高的初始容量使用它,它会影响代码吗?

最佳答案

你检查过HashMap了吗? API Javadoc?

  • 容量是哈希表中的桶数
  • 初始容量就是哈希表创建时的容量
  • 负载因子是衡量哈希表在其容量自动增加之前允许达到多满的量度

关于将初始大小设置得太高:

Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

负载因子对性能的影响:

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.

好吧,简而言之:根据估计的大小和预期的增长率,您必须选择近似值或相反值。

通常,如果您知道 Map 的初始元素数,建议在构建时设置它,避免在初始化时过早重新散列。

关于java - 哪个是 HashMap 的更好选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4932259/

相关文章:

java - JAXB继承+XMLAdapter(HashMap)

java - 在 Enum 类中存储值的 Map 集合以便更好地访问

java - 如何为中间相遇攻击收集数据?

android - 将 HashMap 传递给 AsyncTask 并将其转换为 JSONObject

java - Blackberry "device back"按钮终止应用程序

java - 使用 Maven、Jersey 和 Tomcat 8 从 Intellij 运行 REST 服务

javascript - 使用 JavascriptExecutor selenium 创建一个带有链接作为背景的图像

java - 假设我有一个好的 key ,当不适合在java中使用 map 时

java - 我的应用下载量出乎意料地减少了 10 倍以上

j2mepolish 中的 java.io.File 不工作