What is the HashTable.put() method in Java?
The HashTable.put() method is used to insert key-value pairs in a HashTable.
It is present in the HashTable class inside the java.util package.
Parameters
The HashTable.put() method takes two parameters:
key: The key for the value in theHashTable.value: The value for the key in theHashTable.
Return value
The HashTable.put() method returns the following:
key: The previous value if an existing key is passed.null: If a new pair is passed, thennullis returned.
Code
Let’s look at the below code snippet to understand it better.
import java.util.*;class Main{public static void main(String[] args){Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();h1.put(1, "Let's");h1.put(5, "see");h1.put(2, "Hashtable.contains()");h1.put(27, "method");h1.put(9, "in java.");System.out.println(h1);}}
Explanation
- In line 1, we imported the required package.
- In line 2, we made a
Mainclass. - In line 4, we made a
mainfunction. - In line 6, we declared a
HashTableconsisting ofIntegertype keys andStringtype values. - In lines 8 to 12, we inserted values in the
HashTableby using theHashtable.put()method. - In line 14, we print the
HashTable.
In this way, we can use the HashTable.put() method to insert key-value pairs in the HashTable.