How do I use hashtables?
Hashtables are an extremely useful mechanism for storing data. Hashtables work by mapping a key to a value, which is stored in an in-memory data structure. Rather than searching through all elements of the hashtable for a matching key, a hashing function analyses a key, and returns an index number. This index matches a stored value, and the data is then accessed. This is an extremely efficient data structure, and one all programmers should remember.
Hashtables are supported by Java, in the form of the java.util.Hashtable class. Hashtables accept as keys and values any Java object. You can use a String, for example, as a key, or perhaps a number such as an Integer. However, you can't use a primitive data type, so you'll need to instead use Char, Integer, Long, etc.
// Use an Integer as a wrapper for an int Integer integer = new Integer ( i ); hash.put( integer, data);
Data is placed into a hashtable through the put method, and can be accessed using the get method. It's important to know the key that maps to a value, otherwise its difficult to get the data back. If you want to process all the elements in a hashtable, you can always ask for an Enumeration of the hashtable's keys. The get method returns an object, which can then be cast back to the original object type.
// Get all values with an enumeration of the keys for (Enumeration e = hash.keys(); e.hasMoreElements();) { String str = (String) hash.get( e.nextElement() ); System.out.println (str); }
To demonstrate hashtables, I've written a little demo that adds one hundred strings to a hashtable. Each string is indexed by an Integer, which wraps the int primitive data type. Individual elements can be returned, or the entire list can be displayed. Note that hashtables don't store keys sequentially, so there is no ordering to the list.
import java.util.*; public class hash { public static void main (String args[]) throws Exception { // Start with ten, expand by ten when limit reached Hashtable hash = new Hashtable(10,10); for (int i = 0; i <= 100; i++) { Integer integer = new Integer ( i ); hash.put( integer, "Number : " + i); } // Get value out again System.out.println (hash.get(new Integer(5)));
// Get value out again System.out.println (hash.get(new Integer(21))); System.in.read(); // Get all values for (Enumeration e = hash.keys(); e.hasMoreElements();) { System.out.println (hash.get(e.nextElement())); } } }