Java中的ConcurrentHashMap putIfAbsent()方法
java.util.concurrent.ConcurrentHashMap.putIfAbsent()是Java中的一个内置函数,它接受一个键和一个值作为参数,并将它们映射到一个值,如果指定的键没有映射到任何值。
语法:
chm.putIfAbsent(key_elem, val_elem)
参数: 该函数接受以下两个参数的描述:
- key_elem: 该参数指定将指定的val_elem映射到的键,如果key_elem没有与任何值关联。
- val_elem: 此参数指定要映射到指定的key_elem的值。
返回值: 如果没有将任何值先前映射到该键,则该函数返回映射到该键的现有值,如果没有任何值,则返回null。
异常: 当指定的参数为null时,函数引发NullPointerException。
以下程序说明了ConcurrentHashMap.putIfAbsent()方法:
程序1: 将现有键作为参数传递给函数。
// Java程序演示ConcurrentHashMap的putIfAbsent()方法
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap chm =
new ConcurrentHashMap();
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Gfg");
chm.put(104, "GFG");
// Displaying the HashMap
System.out.println("Initial Mappings are: "
+ chm);
// 插入与值不存在的键
String returned_value = (String)chm.putIfAbsent(108, "All");
// 验证返回值
System.out.println("Returned value is: "
+ returned_value);
// 显示新映射
System.out.println("New mappings are: "
+ chm);
}
}
初始映射为:{100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
返回值为:null
新映射为:{100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG, 108=All}
程序2: 将不存在的键作为参数传递给函数。
//Java程序演示ConcurrentHashMap的putIfAbsent()方法
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap chm =
new ConcurrentHashMap();
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Gfg");
chm.put(104, "GFG");
// Displaying the HashMap
System.out.println("Initial Mappings are: "
+ chm);
// 插入非存在的键值对
String returned_value = (String)chm.putIfAbsent(100, "All");
// 验证返回值
System.out.println("Returned value is: "
+ returned_value);
// 显示新映射
System.out.println("New mappings are: "
+ chm);
}
}
初始映射如下:{100=Geeks,101=for,102=Geeks,103=Gfg,104=GFG}
返回值为:Geeks
新映射如下:{100=Geeks,101=for,102=Geeks,103=Gfg,104=GFG}
参考资料: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#putIfAbsent()
极客教程