In Java, HashTable is a pre-defined class of the collection framework. It is a part of the java.util package and is used to store the key-value pairs in the program. In this article, we will learn how to add and update elements in a HashTable in Java.
Pre-defined Classe to add and update elements in a HashTable
To add or update elements in a HashTable the pre-defined class is:
- HashTable: It is a pre-defined class and it can be used to add or update the elements into the HashMap using the HashTable.
Program to add and update elements in a HashTable in Java
Below is the code implementation to add or update elements in a HashTable.
Java
// Java program to add or update elements in a HashTable import java.util.Hashtable;
import java.util.Map;
public class GFGHashTableExample
{ public static void main(String[] args)
{
// create a HashTable named as hashTable
Hashtable<String, String> hashTable = new Hashtable<>();
// adding elements
hashTable.put( "key1" , "HTML" );
hashTable.put( "key2" , "CSS" );
hashTable.put( "key3" , "JavaScript" );
hashTable.put( "key4" , "ReactJs" );
// printing the elements before update
System.out.println( "Original HashMap" );
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// updating an element
hashTable.put( "key3" , "NodeJs" );
// Printing the elements after update
System.out.println();
System.out.println( "Updated HashMap" );
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
} |
Output
Original HashMap key4: ReactJs key3: JavaScript key2: CSS key1: HTML Updated HashMap key4: ReactJs key3: NodeJs key2: CSS key1: HTML
Explanation of the Program:
- The above Java program demonstrates adding and updating elements in a Hashtable.
-
We have created a Hashtable named
hashTable
and adds key-value pairs into it. - Then the original Hashtable is printed.
- After that, it updates the value associated with the key “key3” to “NodeJs” and prints the Hashtable again to show the changes.