Java - 修改 Hashtable 中的键

在本教程中,我们将了解如何在 Hashtable 中编辑或替换密钥。Java 没有执行此操作的方法,在这种情况下,我们必须编写解决方案。首先,我们将检索要查找的键的值,然后删除旧的键值,最后插入带有旧值的新键.

示例:

 
package com.codeurjava.hashtable;

导入 java.util.*;

public class hashtable_replace_key {

public static void main(String args[]) {

// 创建一个 hashtable
Hashtable ht = new Hashtable();

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

System.out.println(之前的哈希表:”+ht);

//更改键
int key = 2;

// 在我们必须检索要查找的键的值之前
// 并将此值保存在变量中
// 以便我们分配给新键
String val = (String) ht.get(2);

// 删除旧的
ht.remove(key);

// 插入新的键值对
ht.put(22,val);

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

}

}
Runtime:

 
Hashtable before: {3=C, 2=B, 1=A}
Hashtable after: {3=C, 1=A, 22=B}