What is the method for changing values in a hashmap?
To modify the value in a HashMap, you can use the `put` method. This method is used to associate a specified key with a new value, inserting or updating key-value pairs in the HashMap. Below is an example code for modifying values in a HashMap:
import java.util.HashMap;public class Main {
public static void main(String[] args) {
// 创建一个HashMap对象
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加键值对到HashMap
hashMap.put("Key1", 10);
hashMap.put("Key2", 20);
hashMap.put("Key3", 30);
System.out.println("原始HashMap: " + hashMap);
// 修改HashMap中的值
hashMap.put("Key2", 50);
System.out.println("修改后的HashMap: " + hashMap);
}
}
In the sample code above, we first create a HashMap object and add several key-value pairs to it using the `put` method. We then use the `put` method to change the value of the key “Key2” from 20 to 50. Finally, we print out the modified HashMap to verify if the modification was successful.
Running the code will generate the following output:
原始HashMap: {Key1=10, Key2=20, Key3=30}修改后的HashMap: {Key1=10, Key2=50, Key3=30}
In this way, we successfully modified the value in the HashMap.