Java Glossary : Hashtable

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : H words : Hashtable.

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 a Hashtable:

import java.util.Hashtable;
import java.util.Enumeration;
.. .
// create a new Hashtable
Hashtable h = new Hashtable(149 /* capacity */ , 0.75f /* loadfactor */ );
// add some key/value pairs to the Hashtable
h.put( "WA" , "Washington" );
h.put( "NY" , "New York" );
h.put( "RI" , "Rhode Island" );
h.put( "BC" , "British Columbia" );
// look up a key in the Hashtable
String key = "NY";
String stateName = (String) h.get(key);
System.out.println(stateName);
// prints "New York"
// enumerate all the contents of the hashtable
Enumeration keys = h.keys();
while ( keys.hasMoreElements() )
   {
   key = (String )keys.nextElement();
   stateName = (String)h.get(key );
   System.out.println(key + " " + stateName);
   // prints lines of the form NY New York
   // in effectively random order.
   }
// end while

Some fine points:

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:


view

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.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 35427.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/hashtable.html J:\mindprod\jgloss\hashtable.html