Java中的 HashMap replace(key, oldValue, newValue) 方法及示例
Map 接口的replace(K key, V oldValue, V newValue)方法,由HashMap 类实现,用于替换指定key 的旧值,前提是key 之前已经映射到指定的旧值。
句法:
default boolean replace(K key, V oldValue, V newValue)
参数:此方法接受三个参数:
- key:这是必须替换其值的元素的键。
- oldValue:这是必须与提供的键映射的旧值。
- newValue:这是必须与指定键映射的新值。
返回值:如果旧值被替换,此方法返回布尔值true ,否则返回false 。
例外:此方法将抛出:
- NullPointerException如果指定的键或值为空,并且此映射不允许空键或值,并且
- 如果指定键或值的某些属性阻止将其存储在此映射中,则IllegalArgumentException 。
方案一:
// Java program to demonstrate
// replace(K key, V oldValue, V newValue) method
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// Create a HashMap and add some values
HashMap map
= new HashMap<>();
map.put("a", 100);
map.put("b", 300);
map.put("c", 300);
map.put("d", 400);
// print map details
System.out.println("HashMap: "
+ map.toString());
// provide old value, new value for the key
// which has to replace it's old value, using
// replace(K key, V oldValue, V newValue) method
map.replace("b", 300, 200);
// print new mapping
System.out.println("New HashMap: "
+ map.toString());
}
}
输出:
HashMap: {a=100, b=300, c=300, d=400}
New HashMap: {a=100, b=200, c=300, d=400}
方案二:
// Java program to demonstrate
// replace(K key, V oldValue, V newValue) method
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// Create a HashMap and add some values
HashMap map
= new HashMap<>();
map.put("a", 100);
map.put("b", 300);
map.put("c", 300);
map.put("d", 400);
// print map details
System.out.println("HashMap: "
+ map.toString());
// provide old value, new value for the key
// which has to replace it's old value,
// and store the return value in isReplaced using
// replace(K key, V oldValue, V newValue) method
boolean isReplaced = map.replace("b", 200, 500);
// print the value of isReplaced
System.out.println("Old value for 'b' was "
+ "replaced: " + isReplaced);
// print new mapping
System.out.println("New HashMap: "
+ map.toString());
}
}
输出:
HashMap: {a=100, b=300, c=300, d=400}
Old value for 'b' was replaced: false
New HashMap: {a=100, b=300, c=300, d=400}
参考: https: Java/util/HashMap.html#replace-KVV-