Reputation: 167
As stated in the topic, how can I check if Hashtable is full (if one could do that at all)?
Having:
HashMap<Integer, Person> p = new HashMap <>();
I imagine one needs to use e.g.
if (p.size()>p "capacity"==true)
I found somewhere that hashtables are created with a default size 11 and their capacity is automatically increased if needed... So in the end, can Hashtable ever be full?
Upvotes: 1
Views: 2397
Reputation: 41263
The capacity
argument provides a hint to the implementation of an initial size for its internal table. This can save a few internal resizes.
However, a HashMap won't stop accepting put()
s unless the JVM encounters an OutOfMemoryError
.
Under the covers, a hashmap is an array. Hashes are used as array indices. Each array element is a reference to a linked list of Entry
objects. The linked list can be arbitrarily long.
Upvotes: 0
Reputation: 23339
HashMap has a maximum capacity of 1073741824 elements, theoretically
from the source code of HashMap
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
But here it is limited to the number of elements a managed array (used for the backing array) can hold in Java. The JVM might fail with Out of Memory Error when you try to allocate big arrays.
That said, if the HashMap is really awful ( too many populated buckets), the HashMap wouldn't need to allocate or reallocate big arrays because key are not well distributed, it would be allocating more TreeMap
or Lists
nodes depending on the nature of the keys.
Upvotes: 4
Reputation: 726809
Hashtable
s are created with a default size 11
That is not the size of HashTable
, it's the number of hash buckets it has.
Obviously, a table with 11 hash buckets can hold less than 11 items. Perhaps less obviously, a table with 11 buckets may also hold more than 11 items, depending on collision resolution in use.
can
Hashtable
ever be full?
This depends on the implementation. Hash tables that use separate chaining, such as Java's HashMap
, cannot get full, even if all their buckets are exhausted, because we can continue adding items to individual chains of each bucket. However, using too few hash buckets leads to significant loss of performance.
On the other hand, hash tables with linear probing, such as Java's IdentityHashMap
(which is not, strictly speaking, a valid hash-based container), can get full when you run out of buckets.
Upvotes: 4