HashTable Example Java Program


Definition

A hash table is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Syntax

Hashtable variable_name = new Hashtable();

HashTable Example Program

import java.util.Hashtable;
class HashTableExample{
	public static void main(String[] args){
        Hashtable ht = new Hashtable();
        ht.put(1,"FIRST");
        ht.put(2,"SECOND");
        ht.put(3,"THIRD");
		ht.put(4,"THIRD");
        System.out.println("Hashtable is "+ht);
        System.out.println("Value of key 2: "+ht.get(2));
        System.out.println("Size of the Hashtable is  "+ht.size());
    }
}

Sample Output

Output is:
Hashtable is {4=THIRD, 3=THIRD, 2=SECOND, 1=FIRST}
Value of key 2: SECOND
Size of the Hashtable is  4