A HashTable is a collection of key-value pairs. The put
method maps the passed value to the specified key in the Hashtable
.
public V put(K key,V value)
key
: This is the key for the hashtable mapping.value
: This is the value to be associated with the key.If the key is already present in the hashtable, then the old value is replaced with the passed value, and the old value is returned.
If the key is not present in the map, a new key-value pair is inserted and null
is returned.
The key and value argument must not be
null
. Otherwise,NullPointerException
is thrown.
The code below demonstrates how to use the put
method.
import java.util.Hashtable;class PutExample {public static void main( String args[] ) {// create a HashtableHashtable<Integer, String> numbers = new Hashtable<>();// add key-value pairs to the HashtableSystem.out.println("Adding the entry (1-one). The return value is " + numbers.put(1, "one"));System.out.println("Adding the entry (2-Two). The return value is " + numbers.put(2, "Two"));System.out.println("Adding the entry (2-Two). The return value is " + numbers.put(1, "Three"));}}
In the code above, we created a new Hashtable
object with the name numbers
and used the put
method to add mappings for 1
and 2
and update the value for 1
in the map.