8.4 The Hashtable class 

Previous Index Next 


The Hashtable class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.

The following code demonstrates the use of a Hashtable:

Hashtable numbers = new Hashtable();

numbers.put( "one", new Integer(1) );
numbers.put( "two", new Integer(2) );
numbers.put( "three", new Integer(3) );

Integer n = (Integer)numbers.get( "two" );
if ( n != null)
   {
    System.out.println("two = " + n);
   }
The put() method accepts two arguments. A key object and a value object. The key object must implement the hashCode() method and the equals() method. If an entry for the particular key exists, the put() method will replace the entry with the new entry and will return the old entry.

The get() method returns the value object for the specfied key. If the key does not exist in the Hashtable then the get() method returns null. As with the Vector class the get() method returns the value as a refrence to an Object object, so you will need to type cast it to the correct type.
 



Source: