在 Java 中修改哈希表中的值时出现问题

Problem in modifying the value in a HashTable in Java

我在 java 中创建了一个哈希表:Hashtable<Integer, String> h = new Hashtable<Integer, String>();

现在我已经在此哈希表中填充了一些值:

1 -> "A"

2 -> "B"

3 -> "C"

4 -> "D"

现在我想检查哈希表中是否存在特定的 key。如果它确实存在 然后我将修改该特定键的 HashTable 的值部分。 例如 我想检查 key = 2 是否存在。 由于它存在,我想 将值部分 修改为 'F'。

所以现在条目看起来像:2 -> "B F"。

因此哈希表将变为:

1 -> "A"

2 -> "B F"

3 -> "C"

4 -> "D"

谁能给我建议 java 中这个问题的代码。

非常感谢。

嗯,这里不要混淆太多。由于您是新手,请先在此处获取解决方案。

Hash_table.containsKey(key_element); 

您可以将其放入 if 条件并执行您的操作。 这是完整的代码

    // Java code to illustrate the containsKey() method 
import java.util.*; 

public class Hash_Table_Demo { 
    public static void main(String[] args) 
    { 

        // Creating an empty Hashtable 
        Hashtable<Integer, String> hash_table = 
        new Hashtable<Integer, String>(); 

        // Putting values into the table 
        hash_table.put(1, "A"); 
        hash_table.put(2, "B"); 
        hash_table.put(3, "C"); 
        hash_table.put(4, "D"); 


        // Displaying the Hashtable 
        System.out.println("Initial Table is: " + hash_table); 

        // Checking for the key_element '2' 
        if(hash_table.containsKey(2))){ //true
            hash_table.replace(2, "BF");    // Your Soultion Here
        }; 

        System.out.println("New Table is: " + hash_table); 
    } 
}