putIfAbsent() 是 HashMap 在 Java 中的一個實用方法,它屬於 Map 介面。這個方法用來在對應的鍵(key)不存在於映射中時,將一組key,value 放入映射(map)裡。如果映射先前已包含該鍵(key)的映射,則不做任何更動。putIfAbsent() 方法既可以確保不會不小心覆蓋已有的鍵值(key, value),也可以用來在多執行緒環境下安全的更新map,假設映射本身是同步的或者是一個 ConcurrentHashMap。
方法簽名
1
| V putIfAbsent(K key, V value)
|
K: 鍵的類型
V: 值的類型
返回值:如果映射中已經有這個鍵,則返回鍵對應的舊值;如果沒有,則返回 null(並且將新的鍵值對插入映射)。
範例1
以下是使用 putIfAbsent() 方法的一個簡單範例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import java.util.HashMap; import java.util.Map;
public class PutIfAbsentExample { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 90); scores.put("Bob", 80); scores.putIfAbsent("Alice", 95); scores.putIfAbsent("Charlie", 85); scores.forEach((key, value) -> System.out.println(key + ": " + value)); } }
|
範例2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import java.util.HashMap;
class Main { public static void main(String[] args) { HashMap<Integer, String> sites = new HashMap<>();
sites.put(1, "Google"); sites.put(2, "Runoob"); sites.put(3, "Taobao"); System.out.println("sites HashMap: " + sites);
sites.putIfAbsent(4, "Weibo");
sites.putIfAbsent(2, "Wiki"); System.out.println("Updated Languages: " + sites); } }
|