Java - Core Java - Collection Framework - Hashtable


  • The underlying Data Structure is Hash table.
  • Insertion order is not preserved and it is based on hashcode of keys.
  • Duplicate keys are not allowed but values can be duplicated.
  • Heterogeneous objects are allowed for both keys and values.
  • Null is allowed for key and values otherwise we will get runtime exception saying NullPointerException.
  • Hashtable implements Serializable and Cloneable interface but not RandomAccess.
  • Every method present in Hashtable is synchronised and hence Hashtable object is thread safe.
  • Hashtable is the best choice if our frequent operation is search operation.
  • Program
    import java.util.*;
    public class HashTableDemo {
        public static void main(String[] args) {
            Hashtable h= new Hashtable();
            h.put(new Temp(5), "A");
            h.put(new Temp(2), "B");
            h.put(new Temp(6), "C");
            h.put(new Temp(15), "D");
            h.put(new Temp(23), "E");
            h.put(new Temp(16), "F");
    class Temp
        int i;
        Temp(int i)
        public int hashCode()
            return i;
        public String toString()
            return i+"";
    {6=C, 16=F, 5=A, 15=D, 2=B, 23=E}