java - 如何知道/获取hashmap的容量?

标签 java hashmap

<分区>

我很好奇,我在documentation中看到了:

The capacity is the number of buckets in the hash table ... 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.

有没有办法知道 hashmap 在 t 时刻的容量(桶数)?

最佳答案

你需要反射(reflection)

HashMap m = new HashMap();
Field tableField = HashMap.class.getDeclaredField("table");
tableField.setAccessible(true);
Object[] table = (Object[]) tableField.get(m);
System.out.println(table == null ? 0 : table.length);

关于java - 如何知道/获取hashmap的容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23628001/

相关文章:

java - 如何使用扫描仪插入数组列表?

java - 我使用 Drone 和 Selenium 进行 Arquillian 功能测试中的 NullPointerException

java - HashMap 的键值错误

java - java中使用hashmap的字典

kotlin - 在 Kotlin 中复制 map 最聪明的方法是什么?

对于 D3.js 图表,Javascript map 不会返回数组值

java - 在扑克程序中测试两对

带有 "..."数组的 Java 主要方法?

java - 插入从使用 JDBC 中的 POJO 解析的 JSON 检索的多个记录

java - HashSet 和 HashMap 在 Java 中是如何工作的?