Tag Archives: hashtable programming java

Java HashTable with Complete Programming Example

In this chapter you will learn

  1. What is HashTable in Java?
  2. How to implement HashTable?
  3. HashTable programming example in java.

What is HashTable?

Java HashTable class stores item in key/value pair. All the items stored in hashtable is unique and it doesn’t allow null value. It inherits dictionary class and implement the map interface.

To use HashTable in Java you need to add java.util library.

Programming Example

import java.security.Key;
import java.util.*;
class hashtable_example
public static void main(String[] args)
    Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
    //Adding Items  
    System.out.println("Addint Items");  
    hm.put(1, "Steven");
    hm.put(2, "Clark");
    hm.put(3, "Jack");    
    //Remove Item
    System.out.println("Removing Item");
    //Find an Item
    System.out.println("Finding an Item");
     System.out.println("Hi, This is Clark");
        System.out.println("Sorry, this is wrong number");

    //Replace an Item
    System.out.println("Replacing an Item");
    hm.replace(2, "Steven Clark");

    //Traverse Hashtable
    System.out.println("Traversing Through HashTable");
    Set<Integer> keys=hm.keySet();
    for(int i: keys)
        System.out.println("Value of " + i +" = " + hm.get(i));


D:\JavaProgram>javac hashtable_example.java
D:\JavaProgram>java hashtable_example
Addint Items
{3=Jack, 2=Clark, 1=Steven}
Removing Item
{3=Jack, 2=Clark}
Finding an Item
Hi, This is Clark
Replacing an Item
{3=Jack, 2=Steven Clark}
Traversing Through HashTable
Value of 3 = Jack
Value of 2 = Steven Clark


In this tutorial you learned how to use HashTable in java programming. In the next chapter you will learn LinkedHashMap in Java.