In this chapter you will learn
- What is HashTable in Java?
- How to implement HashTable?
- 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"); System.out.println(hm); //Remove Item System.out.println("Removing Item"); hm.remove(1); System.out.println(hm); //Find an Item System.out.println("Finding an Item"); if(hm.get(2)=="Clark") { System.out.println("Hi, This is Clark"); } else { System.out.println("Sorry, this is wrong number"); } //Replace an Item System.out.println("Replacing an Item"); hm.replace(2, "Steven Clark"); System.out.println(hm); //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)); } } }
Output
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
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
Summary
In this tutorial you learned how to use HashTable in java programming. In the next chapter you will learn LinkedHashMap in Java.