Java 如何更改哈希映射中键的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25274987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change the value of a key in a hash map?
提问by pgray10
I have created a hash map that the users input the key and the value. I want to be able to change the value of the hash map if a specific key is entered. I tried the setValue
method but got nothing. The value and the key are both strings. What method would I use to change this?
我创建了一个哈希映射,用户输入键和值。如果输入特定键,我希望能够更改哈希映射的值。我尝试了该setValue
方法,但一无所获。值和键都是字符串。我会用什么方法来改变这个?
回答by Luiggi Mendoza
Just use Map#put
using the current oldkey and the new value:
只需使用Map#put
当前的旧键和新值:
Map<String, String> map = new HashMap<>();
map.put("user", "Luiggi Mendoza");
System.out.println(map);
//replacing the old value
map.put("user", "Oli Charlesworth");
System.out.println(map);
Output:
输出:
{user=Luiggi Mendoza}
{user=Oli Charlesworth}