java - 如果放入 hashmap 超过容量会怎样

标签 java android arraylist hashmap capacity

请告诉我,如果我放入的项数超过指定容量,HashMap 中的旧项会怎样? 例如:

HashMap<String, Bitmap> hashmap= new HashMap<String, Bitmap>(5);

我将容量设置为 5。 但是如果我将 10 个项目放入此 HashMap,前 5 个项目和位图会怎样?

最佳答案

您仅指定初始容量 - HashMap 无论如何都会根据需要增长,并在内部复制内容。它仅作为一种优化提供,因此,如果您知道需要大容量,则可以从该容量开始,这样就不需要复制。

来自documentation :

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

...

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table

关于java - 如果放入 hashmap 超过容量会怎样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23029161/

相关文章:

java - 如何检测空白区域的点击?

android - Realm 实例已经关闭 - 使用 RxJava2

Java For 循环根据条件递增或递减

arrays - 如何在golang中使用for循环将值存储在结构中

java - ArrayList 类中的 toString() 是否被重写

java - Project Euler 5,我得到的答案只有一半,为什么?

java - Android 6.0 Marshmallow - 服务未在 API 23 测试中启动,但在 API 21 上运行良好

java - Microsoft Graph API 访问 token 验证失败 (java)

android - 列出具有交替颜色的项目

Java:如何从查询字符串中删除参数