What is the HashTable.replace() method in Java?
In this shot, we discuss how to use the HashTable.replace() method in Java.
The HashTable.replace() method is present in the HashMapInterface, which is implemented by the HashMap class.
This method is used to replace a key if the key is already mapped with a value.
Parameters
Version 1:
HashTable.replace() takes two parameters.
- Key: The key whose value is to be replaced with a new value in the
HashTable. - New value: The replacement value.
Version 2:
HashTable.replace() takes three parameters.
- Key: The key whose value is to be replaced with a new value in the
HashTable. - Old value: The value of the specified key which goes under replacement.
- New value: Replacement value.
Return
Version 1:
HashTable.replace() returns:
- Value: The old value which was mapped with the key to be replaced.
- Null: It returns this if there was no mapping available with that key passed as an argument.
Version 2:
HashTable.replace() returns a boolean value.
- True: If the value was replaced.
- False: If the value was not replaced.
Code
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);}}
Explanation
- In line 1, we imported the required package.
- In line 2, we made a
Mainclass. - In line 4, we made a
mainfunction. - In line 6, we declared a Hashtable consisting of
Integertype keys andStringtype values. - From lines 8 to 12, we inserted values in the Hashtable by using the
Hashtable.put()method. - In line 14, we displayed the original
Hashtable. - In lines 16 and 17, we used the
HashTable.replace()method to replace the specified key old value with the new value from the HashTable. - In line 19, we displayed the new HashTable, which has the replaced key-value pairs after the usage of
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.