ConcurrentHashMap 類的 replace() 方法僅在當前映射到某個值時才替換鍵的條目。
用法
public V replace(K key, V value)
public boolean replace(K key, V oldValue, V newValue)
參數
key - 與指定值關聯的鍵
oldValue - 預期與指定鍵相關聯的值
newValue - 要與指定鍵關聯的值
返回
如果值被替換,則為真
拋出
NullPointerException 。
例子1
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentHashMapreplaceExample1 {
public static void main(String[] args)
{
// crete a HashMap and add some values
HashMap<String, Integer> mapcon
= new HashMap<>();
mapcon.put("k1", 100);
mapcon.put("k2", 200);
mapcon.put("k3", 300);
mapcon.put("k4", 400);
System.out.println("HashMap values:\n " + mapcon.toString());
//replace the value of key k1 to 1000
mapcon.replace("k1" , 1000);
System.out.println("New HashMap after remove:\n "+ mapcon);
}
}
輸出:
HashMap values: {k1=100, k2=200, k3=300, k4=400} New HashMap after remove: {k1=1000, k2=200, k3=300, k4=400}
例子2
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentHashMapreplaceExample2 {
public static void main(String[] args)
{
// crete a HashMap and add some values
HashMap<String, Integer> mapcon
= new HashMap<>();
mapcon.put("k1", 100);
mapcon.put("k2", 200);
mapcon.put("k3", 300);
mapcon.put("k4", 400);
System.out.println("HashMap values:\n " + mapcon.toString());
//replace the value of key k2 to 2000
mapcon.replace("k2" , 200 , 2000);
System.out.println("New HashMap after remove:\n "+ mapcon);
}
}
輸出:
HashMap values: {k1=100, k2=200, k3=300, k4=400} New HashMap after remove: {k1=100, k2=2000, k3=300, k4=400}
相關用法
- Java ConcurrentHashMap remove()用法及代碼示例
- Java ConcurrentHashMap contains()用法及代碼示例
- Java ConcurrentHashMap newKeySet()用法及代碼示例
- Java ConcurrentHashMap elements()用法及代碼示例
- Java ConcurrentHashMap forEach()用法及代碼示例
- Java ConcurrentHashMap putIfAbsent()用法及代碼示例
- Java ConcurrentHashMap computeIfAbsent()用法及代碼示例
- Java ConcurrentHashMap isEmpty()用法及代碼示例
- Java ConcurrentHashMap equals()用法及代碼示例
- Java ConcurrentHashMap putAll()用法及代碼示例
- Java ConcurrentHashMap mappingCount()用法及代碼示例
- Java ConcurrentHashMap merge()用法及代碼示例
- Java ConcurrentHashMap hashcode()用法及代碼示例
- Java ConcurrentHashMap containsKey()用法及代碼示例
- Java ConcurrentHashMap put()用法及代碼示例
- Java ConcurrentHashMap computeIfPresent()用法及代碼示例
- Java ConcurrentHashMap toString()用法及代碼示例
- Java ConcurrentHashMap clear()用法及代碼示例
- Java ConcurrentHashMap size()用法及代碼示例
- Java ConcurrentHashMap keys()用法及代碼示例
注:本文由純淨天空篩選整理自 Java ConcurrentHashMap replace() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。