![]() |
VOOZH | about |
The replace(key, oldValue, newValue) method of the HashMap class in Java is used to conditionally replace the value of a specified key if, and only if, the current value matches the specified old value.
Example 1: This example demonstrates replacing a value only if the key is mapped to the given old value.
Original map: {1=Geek1, 2=Geek2, 3=Geek3}
Was value replaced? true
Updated map: {1=Geek1, 2=Geek10, 3=Geek3}
boolean replace(K key, V oldValue, V newValue)
Parameters:
Return Type:
This method returns "true" if the value associated with the key is replaced successfully or return "false" if the key does not exist in the map.
Exception:
Example 2: This example shows what happens when the old value provided does not match the current value.
Initial HashMap: {1=Java, 2=C++, 3=Python}
Was replacement successful? false
Updated HashMap: {1=Java, 2=C++, 3=Python}
Example 3: This example demonstrates that if the key does not exists, the method returns false.
Initial HashMap: {1=Java, 2=C++}
Was replacement successful? false
Updated HashMap: {1=Java, 2=C++}