In this shot, we discuss how to use the HashTable.replace()
method in Java.
The HashTable.replace()
method is present in the HashMap
Interface, which is implemented by the HashMap
class.
This method is used to replace a key if the key is already mapped with a value.
HashTable.replace()
takes two parameters.
HashTable
.HashTable.replace()
takes three parameters.
HashTable
.HashTable.replace()
returns:
HashTable.replace()
returns a boolean value.
Let’s have a look at the code.
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.remove()");h1.put(27, "method");h1.put(9, "in java.");System.out.println("The Hashtable is: " + h1);h1.replace(5,"see","have a look on");h1.replace(27,"method","function");System.out.println("The new Hashtable is: " + h1);}}
Main
class.main
function.Integer
type keys and String
type values.Hashtable.put()
method.Hashtable
.HashTable.replace()
method to replace the specified key old value with the new value from the HashTable.HashTable.replace()
method.In this way, we can use the HashTable.replace()
method to replace the key if it is already mapped with a value.