【问题标题】:Problem in modifying the value in a HashTable in Java在 Java 中修改 HashTable 中的值的问题
【发布时间】:2020-04-20 08:08:53
【问题描述】:

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

现在我在这个 Hashtable 中填充了一些值:

1 -> “A”

2 -> "B"

3 -> "C"

4 -> "D"

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

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

所以 Hashtable 会变成:

1 -> “A”

2 -> "B F"

3 -> "C"

4 -> "D"

有人可以建议我用java解决这个问题的代码吗?

非常感谢。

【问题讨论】:

  • 请展示一些你做过的代码或工作,这很简单。
  • 请注意 Hashtable 是一个过时的集合。 stackoverflow.com/questions/8223125/…
  • 人们还在使用Hashtable?它被弃用 22 年后?

标签: java hashtable


【解决方案1】:

好吧,不要在这里混淆太多。由于您是新手,请先在这里获得解决方案。

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); 
    } 
} 

【讨论】:

  • 如果你使用containsKey(),为什么还要使用replace()?它是Java 8中添加的辅助方法,相当于if (map.containsKey(key)) { map.put(key, value); },所以说documentation,所以containsKey()replace()都用是多余的。
猜你喜欢
  • 2015-05-19
  • 2012-03-27
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
相关资源
最近更新 更多