Java - modify a key in Hashtable
In this tutorial, we'll look at how to edit or replace a key in Hashtable. Java doesn't have a method that does this, and in this case we have to write our solution. First, we will retrieve the value of the key we are looking for, then delete the old key-value and at the end insert the new key with the old value.Example:
Runtime:
package com.codeurjava.hashtable;
import java.util.*;
public class hashtable_replace_key {
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: "+ht);
//key to change
int key = 2;
// before we have to retrieve the value of the key we are looking for
// and save this value in a variable
// so that we assign to the new key
String val = (String) ht.get(2);
// delete the old
ht.remove(key);
// insert the new key-value pair
ht.put(22,val);
System.out.println("Hashtable after: "+ht);
}
}
Hashtable before: {3=C, 2=B, 1=A}
Hashtable after: {3=C, 1=A, 22=B}