在 Java 中更新 Hashmap 的值
本文介绍了如何在 Java 中使用 HashMap 类中包含的两个方法-put() 和 replace() 更新 HashMap 中的值。
在 Java 中使用 hashmap.put() 更新 Hashmap 中的值
当我们要在 HashMap 中插入一个值时,我们使用 put() 方法。而我们也可以用它来更新 HashMap 里面的值。在下面的例子中,我们创建了一个 HashMap 的对象,这个对象是由键值对组成的,在初始化的时候需要定义键和值的数据类型。
我们对键和值都使用字符串类型,我们可以使用键查找或对值进行操作。下面,我们用一个新的值来替换有 key three 的值。如果在 HashMap 中没有我们想要更新的存在,使用 put() 方法,就会插入一个新的值。输出显示的是更新后的值。
import java.util.HashMap;
public class UpdateHashmap {
public static void main(String[] args) {
HashMap<String, String> ourHashmap = new HashMap<>();
ourHashmap.put("one", "Alex");
ourHashmap.put("two", "Nik");
ourHashmap.put("three", "Morse");
ourHashmap.put("four", "Luke");
System.out.println("Old Hashmap: " + ourHashmap);
ourHashmap.put("three", "Jake");
System.out.println("New Hashmap: " + ourHashmap);
}
}
输出:
Old Hashmap: {four=Luke, one=Alex, two=Nik, three=Morse}
New Hashmap: {four=Luke, one=Alex, two=Nik, three=Jake}
在 Java 中使用 hashmap.replace() 更新 Hashmap 中的值
HashMap 类的另一个方法是 replace(),它可以更新或替换 HashMap 中的现有值。put() 和 replace() 的最大区别是,当 HashMap 中不存在一个键时,put() 方法会把这个键和值插入 HashMap 里面,但 replace() 方法会返回 null。这使得 replace() 在更新 HashMap 中的值时,使用 replace() 更加安全。
在下面的例子中,我们创建一个 HashMap 并插入一些键值对。然后更新附加在键 three 上的值,我们使用 ourHashMap.replace(key, value),它需要两个参数,第一个是我们要更新的键,第二个是值。
import java.util.HashMap;
public class UpdateHashmap {
public static void main(String[] args) {
HashMap<String, String> ourHashmap = new HashMap<>();
ourHashmap.put("one", "Alex");
ourHashmap.put("two", "Nik");
ourHashmap.put("three", "Morse");
ourHashmap.put("four", "Luke");
System.out.println("Old Hashmap: " + ourHashmap);
ourHashmap.replace("three", "Jake");
System.out.println("New Hashmap: " + ourHashmap);
}
}
输出:
Old Hashmap: {four=Luke, one=Alex, two=Nik, three=Morse}
New Hashmap: {four=Luke, one=Alex, two=Nik, three=Jake}
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn