How to use Hashtable.put method in Java?

A HashTable is a collection of key-value pairs. The put method maps the passed value to the specified key in the Hashtable.

Syntax

public V put(K key,V value)

Parameters

  • key: This is the key for the hashtable mapping.
  • value: This is the value to be associated with the key.

Return value

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.

Code

The code below demonstrates how to use the put method.

import java.util.Hashtable;
class PutExample {
public static void main( String args[] ) {
// create a Hashtable
Hashtable<Integer, String> numbers = new Hashtable<>();
// add key-value pairs to the Hashtable
System.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"));
}
}

Explanation

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.

Free Resources