Hashtable class is part of java.util package. Hashtable class can add key and value put(key, value) pair elements. Hashtable do not permit null key and value. But Hashtable is synchronized. Hashtable class return ordered entry as entered.
Hashtable extends Dictionary class and implements Map interface. Key and value of Hashtable can get by Set Interface and Map interface through Iterator and Enumeration interface.
Hashtable example give a method, how to use Hashtable in java
1. Hashtable example with Enumeration
import java.util.Hashtable; import java.util.Enumeration; public class HashTableExample { public static void main(String[] args) { Hashtable<Integer,String> hTable=new Hashtable<Integer,String>(); //adding or set items in Hashtable by put method key and value pair hTable.put(new Integer(2), "Two"); hTable.put(new Integer(1), "One"); hTable.put(new Integer(4), "Four"); hTable.put(new Integer(3), "Three"); hTable.put(new Integer(5), "Five"); // Get Hashtable Enumeration to get key and value Enumeration em=hTable.keys(); while(em.hasMoreElements()) { //nextElement is used to get key of Hashtable int key = (Integer)em.nextElement(); //get is used to get value of key in Hashtable String value=(String)hTable.get(key); System.out.println("Key :"+key+" value :"+value); } } }
2. Hashtable example with Enumeration
import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.util.Map; public class HashTableJava { public static void main(String[] args) { Hashtable<Integer,String> hTable=new Hashtable<Integer,String>(); hTable.put(new Integer(2), "Two"); hTable.put(new Integer(1), "One"); hTable.put(new Integer(4), "Four"); hTable.put(new Integer(3), "Three"); hTable.put(new Integer(5), "Five"); Set s =hTable.entrySet(); Iterator i=s.iterator(); while(i.hasNext()) { Map.Entry m=(Map.Entry)i.next(); int key = (Integer)m.getKey(); String value=(String)m.getValue(); System.out.println("Key :"+key+" value :"+value); } } }
Output
Key :5 value :Five
Key :4 value :Four
Key :3 value :Three
Key :2 value :Two
Key :1 value :One
Tags: Collections




Link to Us
Please correct the caption for second example.
In place of “Hashtable example with Enumeration”
“Hashtable example with Iterator” should be there.