HashTable
● is variable collection of key-value pairs
● can't contain duplicate keys (each key can map to at most one value)
Both keys and values can be any Object or Primitive Type.
Use HashMap instead Hashtable since
● it allows null values for both keys and values
● it's iterator is fail-safe throwing Exception if another thread tries to modify collection "structurally" while iterating
● it is not thread-safe making it faster and giving you an option to synchronize it or not
Test.java
import java.util.Enumeration;
import java.util.Hashtable;
public class Test {
public static void main (String arg[]) throws Exception {
//PUT ELEMENTS.-------------------------------------------
Hashtable hashtable = new Hashtable();
hashtable.put("key" , "element" ); //Add key-value pair.
hashtable.put("age" , 33 );
hashtable.put(new Integer(34) , false );
hashtable.put(1 , new Character('A') );
//GET ELEMENTS.-------------------------------------------
String name = (String ) hashtable.get ("key" );
int age = ( (Integer ) hashtable.get ("age" ) ).intValue ();
boolean flag = ( (Boolean ) hashtable.get (new Integer(34) ) ).booleanValue ();
char stuff = ( (Character) hashtable.get (1 ) ).charValue ();
//STATISTICS.---------------------------------------------
boolean containsElement = hashtable.contains ("element");
boolean containsElement2 = hashtable.containsValue("element");
boolean containsKey = hashtable.containsKey ("key" );
boolean isEmpty = hashtable.isEmpty ( );
int size = hashtable.size ( );
String removed = (String) hashtable.remove ("key" );
hashtable.clear ( );
//DISPLAY KEYS.-------------------------------------------
Enumeration keys = hashtable.keys();
while( keys .hasMoreElements()== true ) {
System.out.println(keys.nextElement());
}
//DISPLAY ELEMENTS.---------------------------------------
Enumeration elements = hashtable.elements();
while( elements.hasMoreElements() == true ) {
System.out.println(elements.nextElement());
}
//DISPLAY STATISTICS.-------------------------------------
System.out.println ("Contains 'element' = " + containsElement );
System.out.println ("Contains 'element' = " + containsElement2);
System.out.println ("isEmpty = " + isEmpty );