Java - Edit a value in Hashtable

Suppose we have a Hashtable< String, Integer> in Java. How to change or override the value for a given key.

Example of the java.util.Hashtable.put(K key, V value)

This method is used to bind the key to a value in a hashtable. The exception  NullPointerException  is triggered  if the key or values are zero. If the key already exists, its value is automatically replaced.

The example below shows changing a value.

 
package com.codeurjava.hashtable;

import java.util.*;

public class hashtable_put {

public static void main(String args[]) {
// create a hashtable
Hashtable ht = new Hashtable();

// insert peers
ht.put(1, "A");
ht.put(2, "B");
ht.put(3, "C");

System.out.println("Hashtable before modification: "+ht);

// change the value of the 2
String val_ret=(String)ht.put(2,"BB");

System.out.println("Replaced value: "+val_ret);

System.out.println("Hashtable after modification: "+ht);

}

}
Runtime:

 
Initial hash table value: {3=C, 2=B, 1=A}
Replaced value: B
New Hashtable: {3=C, 2=BB, 1=A}

Example of the replace()

Java has another replace().
  • public  boolean replace(K  key, V  oldValue, V  newValue)
There is no difference between the put and replace() methods in this case where there is already an assignment between the key and the value and you want to override.

ht.replace(2,"B", "BB"); 
Ressources:
https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#put(K,%20V)