这个 JAVAutil。同时发生的ConcurrentHashMap。putIfAbsent() 是Java中的一个内置函数,它接受一个键和一个值作为参数,并在指定的键未映射到任何值时映射它们。
null
语法:
chm.putIfAbsent(key_elem, val_elem)
参数: 该函数接受以下两个参数:
- 关键要素: 此参数指定指定的 瓦勒姆 如果 基尤埃伦 与任何值都不关联。
- 瓦勒姆: 此参数指定要映射到指定值的值 基尤埃伦 .
返回值: 函数返回映射到键的现有值,如果之前没有值映射到键,则返回null。
例外情况: 函数抛出 空指针异常 当指定的参数为空时。
下面的程序演示了ConcurrentHashMap。putIfAbsent()方法:
项目1: 现有密钥作为参数传递给函数。
// Java Program Demonstrate putIfAbsent() // method of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); 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); // Inserting non-existing key along with value String returned_value = (String)chm.putIfAbsent( 108 , "All" ); // Verifying the returned value System.out.println( "Returned value is: " + returned_value); // Displayin the new map System.out.println( "New mappings are: " + chm); } } |
输出:
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG} Returned value is: null New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG, 108=All}
项目2: 不存在的密钥作为参数传递给函数。
// Java Program Demonstrate putIfAbsent() // method of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); 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); // Inserting existing key along with value String returned_value = (String)chm.putIfAbsent( 100 , "All" ); // Verifying the returned value System.out.println( "Returned value is: " + returned_value); // Displayin the new map System.out.println( "New mappings are: " + chm); } } |
输出:
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG} Returned value is: Geeks New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
参考 : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#putIfAbsent()
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END