Java Hashtable put() Method
The Hashtable.put() method is a part of java.util package. This method is used to insert a mapping into a table. This means we can insert a specific key and the value it maps to into a particular table. If an existing key is passed, then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
Syntax of Hashtable put() Method
Below is the syntax of put() method.
Hash_Table.put(key, value)
Parameters:
This method takes two parameters, both of the Object type of the Hashtable.
- key: This refers to the key element that needs to be inserted into the table for mapping.
- value: This refers to the value that the above key will map to.
Return Value: If an existing key is passed, the previous value gets returned. If a new pair is passed, then null is returned.
Examples of Java Hashtable put() Method
Example 1: In this example, we are going to use the put() method when an existing key is passed.
// Java program to demonstrate Hashtable.put() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Create an empty Hashtable
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
// Insert values into the Hashtable
ht.put(10, "Geeks");
ht.put(15, "4");
ht.put(20, "Geeks");
ht.put(25, "Welcomes");
ht.put(30, "You");
System.out.println("Initial table is: " + ht);
// Insert existing key along with a new value
String returned = ht.put(20, "All");
// Verify the returned value
System.out.println("Returned value is: " + returned);
System.out.println("New table is: " + ht);
}
}
Example 2: In this example, let's use the put() method when a new key is passed and we will see what it prints.
// Java program to demonstrate Hashtable.put() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Create an empty Hashtable
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
// Insert values into the Hashtable
ht.put(10, "Geeks");
ht.put(15, "4");
ht.put(20, "Geeks");
ht.put(25, "Welcomes");
ht.put(30, "You");
System.out.println("Initial table is: " + ht);
// Insert new key along with a value
String returned = ht.put(50, "All");
// Verify the returned value
System.out.println("Returned value is: " + returned);
System.out.println("New table is: " + ht);
}
}
Important Points:
- The put() method replaces the value if the key is already exists.
- The method returns the previous value associated with the key or it returns null if the key was not present.
- This method works with any combination of data types as the key and value.