Java Tutorial

Hash Table

Hash table

Hashtable is the concrete sub-class of duplicates and where object allows us to store in the form of (key, value) pair. Hashtable object organizes its data by following hashing mechanism. We cannot determine in which order the Hashtable displays its data.

Hash table API:


Hashtable ();

Instance methods:

public boolean put (Object kobj, Object vobj); -71 
public void remove (Object kobj); -72
public Object get (Object kobj); -73 
public Enumeration keys (); -74

Method-1 is used for obtaining value object by passing key object. If the key object is not found then the value object is null. Method-2 is used for extracting key objects from Hashtable.

Write a java program which illustrates the concept of Hashtable?


import java.util.*;

class hashtable {

    public static void main(String[] args) {
        Hashtable ht = new Hashtable();
        ht.put("AP", "Hyd");
        ht.put("Orissa", "Bhuvaneshwar");
        ht.put("Karnatake", "Bng");
        ht.put("TN", "Chennai");
        ht.put("Bihar", "Patna");
        Enumeration en = ht.keys();
        while (en.hasMoreElements()) {
            Object k = en.nextElement();
            Object v = ht.get(k);
            System.out.println(k + "	" + v);
        if (args.length == 0) {
            System.out.println("PASS THE STATE");
        } else {
            String st = args[0];
            Object cap = ht.get(st);
            if (cap == null) {
                System.out.println(cap + " IS THE CAPITAL OF " + st);