I am curious, I read in the 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.
Is there a way to know the capacity (number of buckets) of the hashmap at an instant t?
You need 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);
If you look at the online API, you'll see that there aren't any publicly available methods that will tell you that. There's always reflection, but I wouldn't recommend that.
In any case, that could be considered an implementation detail that you shouldn't rely in most cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With