Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know/get the capacity of hashmap? [duplicate]

Tags:

java

hashmap

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?

like image 556
GermainGum Avatar asked May 13 '14 09:05

GermainGum


2 Answers

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);
like image 112
Evgeniy Dorofeev Avatar answered Sep 21 '22 10:09

Evgeniy Dorofeev


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.

like image 29
awksp Avatar answered Sep 21 '22 10:09

awksp