Java Utility Library

Java Hashtable - replace() Method



The java.util.Hashtable.replace() method is used to replace the entry for the specified key only if it is currently mapped to some value.

Syntax

public V replace(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is associated.
value Specify the value to be associated with the specified key.

Return Value

Returns the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key, if the implementation supports null values.)

Exception

NA.

Example:

In the example below, the java.util.Hashtable.replace() method is used to replace the entry for the specified key in the given hashtable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hashtable
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

    //populating hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");

    //printing hashtable
    System.out.println("Before replace, Htable contains: " + Htable);    

    //replacing the value associated with 101 key
    Htable.replace(101, "Sam"); 

    //printing hashtable
    System.out.println("After replace, Htable contains: " + Htable);  
  }
}

The output of the above code will be:

Before replace, Htable contains: {103=Kim, 102=Marry, 101=John}
After replace, Htable contains: {103=Kim, 102=Marry, 101=Sam}

❮ Java.util - Hashtable