posted 4 years ago
Because even if there are less items in the map than there are buckets (meaning there are empty buckets available), some buckets may still contain more than one item. The reason for this is that HashMap doesn't look for an empty bucket to put items in. Instead, it calculates a bucket index from the hash code of the item and the current capacity of the map, and puts the item in that bucket, regardless of whether there's already an item in the bucket. This is the reason that HashMap is so fast: It doesn't spend time looking for an empty bucket.
It's true that HashMap will slow down if it gets fuller, because there are more and more collisions and performance will degrade from constant lookup times to logarithmic lookup times (because it now has to look for items in a tree, rather than a hash table). This is why the map doesn't wait for itself to get full before it resizes. Instead, it resizes when its size has reached a certain percentage of its capacity. This percentage is known as the load factor. By default, the load factor is 75%. This means that by default, 25% of all buckets in a HashMap will be unused. This may seem wasteful, but it ensures that there are almost no collisions and that lookups will remain super fast.