Hashtable : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

Hashtable

For Strings, Hashtables work pretty much as you would expect if you are familiar with hashing. The only catch is remembering to import java.util.Hashtable (with a small t in table). Here is how you use

The key point for novices to remember is the capacity of the table has to be somewhat larger than the number of elements you plan to look up. The more spare capacity you give, the faster the lookup. There are, of course, diminishing returns. Typically, you specify about 25% more capacity than you have elements and a load factor of 0.75 which controls automatic growth of the lookup table when it gets too full. More details on that later.

The capacity of a table is not the number of elements you plan to add! If you specify a capacity of 100 and a load factor of .75, Hashtable will allocate only 100 slots, not the 133 you need for efficient access. The load factor kicks in only when deciding when it is time to double the size of the table, in this case, just after you have added 75 elements, not in deciding its initial size. It is up to you to leave some breathing room.

Tips

Dealing With Duplicates

Hashtables don’t permit duplicates. What do you do if some of your objects have duplicate keys? When you have duplicates, what do you want to find when you do a lookup? Just the first, just the last? both? If you are clever, you ca get all those behaviours with a Hashtable.

To get the first duplicate, before you put, do a check to see if the element is already in the Hashtable, if so, do nothing.

To get the last duplicate, just put. It will replace what was there before. To get both, store an ArrayList as the value. Store each of the duplicates in one of the slots of the ArrayList. This is a bit inefficient for non-duplicates. For them, you could store just the plain Object. Any you might handle the special case of just one duplicate with an array. Your logic might look a bit like this:

Of course, are free to simplify the algorithm, going straight to ArrayLists even for singles. My complex recipe is designed to conserve RAM on large lists.

Oracle’s Javadoc on Hashtable class : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/hashtable.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\hashtable.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[44.222.149.13]
You are visitor number