Michael - no, the time required for a
single fetch is (on avarage) constant, regardless of the number of elements in the Map. However 100 fetches will take approximately 100 times as long as a single fetch.
Also, from Mike's post:
If you know that your HashMap will only contain say, 20 elements, then you would be prudent to initialize your HashMap like this:
Map myMap = new HashMap(20, 1.0f);
This will cause the HashMap to create an array internally with room for 20 elements
This is a bit misleading. I would usually want to set the capacity a bit higher than the maximum number of elements expected in the HashMap, because this will reduce the number of collisions in the map.
Imagine it this way - if the capacity is set to 20 (meaning the internal array has size 20), and you insert 20 elements, each element will be assigned a position in the array according to the element's (hashCode() % 20) - which (for a good hash function) is like a random number. (Unless two elements are equal - assume they're not.) Now there's a chance that all 20 elements will end up in completely different array positions. But much more likely, some will end up in the same position. This is called a collision. Certainly if a 21st element were added, we'd guarantee that at least one collision would occur. But even for 20, it's exptremely likely that at several elements will by chance end up sharing array positions. The hashtable will then store a linked list at that array position, which contains all the elements sharing that array position. Whenever someone needs to access one of these elements, the system will loop through the linked list to find the right element. This adds to the HashMap's exectution time. Thus, collisions can be resolved, but we try to avoid them. If the expected number of elements to be stored in the HashMap is 20, setting the capacity to something like 40 will greatly reduce the number of collisions, and thus improve performance. It's a classic memory vs. speed tradeoff of course - but 20 elements is pretty insignificant on most machines, so I'd use the extra memory here without a second thought.