Pergunta

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?

Foi útil?

Solução

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);

Outras dicas

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.

No such public method in HashMap.

You could use debug mode in your IDE to watch HashMap.table.

plus: as Sanjeev commented, reflection is an option.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top