HashMap類實現的Map接口的replace(K key,V oldValue,V newValue)方法僅在先前將鍵映射為指定的舊值時才用於替換指定鍵的舊值。
用法:
default boolean replace(K key, V oldValue, V newValue)
參數:此方法接受三個參數:
- key:這是必須替換其值的元素的鍵。
- oldValue:這是舊值,必須使用提供的鍵進行映射。
- newValue:這是必須與指定鍵映射的新值。
返回值:如果替換了舊值,則此方法返回布爾值true,否則返回false。
異常:該方法將拋出:
- NullPointerException 如果指定的鍵或值是null,並且此映射不允許空鍵或值,並且
- IllegalArgumentException如果指定鍵或值的某些屬性阻止將其存儲在此映射中。
程序1:
// 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<String, Integer> 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}
程序2:
// 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<String, Integer> 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://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#replace-K-V-V-
相關用法
- Java HashMap putIfAbsent(key, value)用法及代碼示例
- Java HashMap computeIfAbsent()用法及代碼示例
- Java HashMap compute()用法及代碼示例
- Java HashMap replace(key, value)用法及代碼示例
- Java HashMap replaceAll(BiFunction)用法及代碼示例
- Java HashMap computeIfPresent(key, BiFunction)用法及代碼示例
- Java HashMap forEach(BiConsumer)用法及代碼示例
- Java HashMap getOrDefault(key, defaultValue)用法及代碼示例
- Java HashMap merge(key, value, BiFunction)用法及代碼示例
- Java HashMap get()用法及代碼示例
- Java HashMap put()用法及代碼示例
- Java HashMap containsKey()用法及代碼示例
注:本文由純淨天空篩選整理自iamvineettiwari012大神的英文原創作品 HashMap replace(key, oldValue, newValue) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。