Hashtables and HashMaps
Because
Hashtables and
HashMaps are the most commonly used nonlist
structures, I will spend a little extra time discussing them.
Hashtables and HashMaps are
pretty fast and provide adequate performance for most purposes. I
rarely find that I have a performance problem using
Hashtables or HashMaps, but
here are some points that will help you tune them, or, if necessary,
replace them:
Hashtableissynchronized. That’s fine if you are using it to share data across threads, but if you are using it single-threaded, you can replace it with an unsynchronized version to get a small boost in performance.HashMapis an unsynchronized version available from JDK 1.2.Hashtables andHashMaps are resized whenever the number of elements reaches the [capacity *loadFactor]. This requires reassigning every element to a new array using the rehashed values. This is not simply an array copy; every element needs to have its internal table position recalculated using the new table size for the hash function. You are usually better off setting an initial capacity that handles all the elements you want to add. This initial capacity should be the number of elements divided by theloadFactor(the default load factor is 0.75).Hashtables andHashMaps are faster with a smallerloadFactor, but take up more space. You have to decide how this tradeoff works best for you.The hashing function should work better with a capacity that is a prime number. Failing this, always use an odd ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access