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 the specified value.

Syntax

public boolean replace(K key, V oldValue, V newValue)

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.
oldValue Specify value expected to be associated with the specified key.
newValue Specify value to be associated with the specified key.

Return Value

Returns true if the value was replaced.

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, "John", "Sam");
    //replacing the value associated with 102 key
    //it is not replaced as oldValue is not matching
    Htable.replace(102, "Jo", "Peter");     

    //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