Skip to content

Replace Value for a Key in Java Hashtable Example

This example shows how to replace a value for the key in Hashtable in Java. This example also shows how to replace the value for a key using the put method and replace method.

How to replace the value for a key in Hashtable in Java?

There are a couple ways using which we can replace a value mapped to the hashtable key.

1. Using the replace method

The Hashtable replace method replaces the value mapped to the specified key with the specified new value.

It replaces the old value with the given new value for the key in the hashtable object and returns an old value. If the key does not exist in the hashtable, it returns null.

Output

The above given replace method replaces the value of the key if the key is mapped to any value in the hashtable. If you want to replace the value for a key if and only if it is mapped to a specific value, then use the overloaded replace method.

It replaces the old value with the given new value and returns true if the key exists in the hashtable and it is mapped to the given old value. If the key does not exist in the hashtable or if the key exists but not mapped to the given old value, it returns false.

Output

2. Using the put method (not recommended)

The Hashtable put method also replaces the value for the given key in the hashtable, if the key exists.

Using the put method for the replacement purpose is not recommended because if the specified key does not exist in the hashtable, it creates a new mapping.

This example is a part of the Java Hashtable Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Hashtable Documentation

About the author

Leave a Reply

Your email address will not be published.