请告诉我,如果我放入的项数超过指定容量,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/