auser
auser

Reputation: 7497

How does initial capacity impact the performance of a HashMap

The documentation for HashMap contains the following statement:

Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

Could someone please explain it. I don't see any method for changing or affecting the load factor of a HashMap

Upvotes: 3

Views: 1059

Answers (3)

user395760
user395760

Reputation:

Both a too large initial capacity and a too low load factor result in a hash table where most entries are vacant. While this decreases the odds of collisions (and thus improves average lookup performance), iterating over the keys/values/items of the hash table requires skipping over more empty slots.

As others have explained, you can give a load factor and initial capacity when constructing the hash table object.

Upvotes: 2

utopianheaven
utopianheaven

Reputation: 1277

There's a lot of theory behind a hash table and what makes a "good" hash table for a given input set prediction, I would start with the Wikipedia article (specifically at the "Load Factor" section that's linked).

Upvotes: 0

Eric B.
Eric B.

Reputation: 24411

When you declare your HashMap as part of the constructor argument, you can provide it with both the initial capacity and the load factor:

 HashMap(int initialCapacity, float loadFactor) 
     Constructs an empty HashMap with the specified initial capacity and load factor.

You can also look at this SO thread for some insight on Load Factors and Initial Capacity.

Upvotes: 2

Related Questions