Java - Hashtable example

Posted on October 25, 2016


Hashtable class implements the hash table which maps keys to values. The Hashtable class does not permit null as a key or value. Objects used as key for the Hashtable class must implement the hashCode method and  the equals method. 

The basic methods used in the Hashtable are 

  • put() - add new element (key-value) into the Hashtable.
  • get() - return value by passing key.
  • remove() - remove key and value from  the Hashtable.
  • size() - return size of hashtable.
  • containsKey() - return true if key exist in  the Hashtable otherwise return false.
  • containsValue() - return true if value exist in the Hashtable otherwise return false.
  • clear() - remove all elements from the Hashtable ​​​​​​.

HashTableExample.java

package com.boraji.tutorial;

import java.util.Hashtable;

/**
 * @author imssbora
 *
 */
public class HashTableExample {
	public static void main(String[] args) {
		Hashtable<String, String> hashtable=new Hashtable<>();
		/*Adding key and values in Hashtable*/
		hashtable.put("1", "One");
		hashtable.put("2", "Two");
		hashtable.put("3","Three");
		hashtable.put("4", "Four");
		hashtable.put("5", "Five");
		
		System.out.println("Hashtable key-values are:"+hashtable);
		
		/*Get value by key from the Hashtable*/
		System.out.println("Value of '4' is: "+hashtable.get("4"));
		
		/*Removing key and value from the Hashtable	*/
		hashtable.remove("4");
		System.out.println("After removal, Hashtable Key-Value: " +hashtable);
		
		/*Getting size of Hashtable*/
		System.out.println("Size of Hashtable is : "+hashtable.size());
		
		/*Checking if key exist in the Hashtable or not*/
		System.out.println("Key '3' exist: "+hashtable.containsKey("3"));
		
		/*Checking if value exist in the Hashtable or not*/
		System.out.println("Key '6' exist: "+hashtable.containsValue("6"));
		
		/*Remove all keys and values from the Hashtable*/
		hashtable.clear();
		System.out.println("After clearing Hashtable: "+hashtable);
	}
}

Output

Hashtable key-values are:{5=Five, 4=Four, 3=Three, 2=Two, 1=One}
Value of '4' is: Four
After removal, Hashtable Key-Value: {5=Five, 3=Three, 2=Two, 1=One}
Size of Hashtable is : 4
Key '3' exist: true
Key '6' exist: false
After clearing Hashtable: {}