当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ConcurrentHashMap get()用法及代码示例


java.util.concurrent.ConcurrentHashMap的get()方法是Java中的内置函数,它接受键作为参数并返回映射到它的值。如果作为参数传递的键不存在映射,则返回null。

用法:

Concurrent.get(Object key_element)

参数:该方法接受对象类型的单个参数key_element,该参数表示应该返回其关联值的键。


返回值:该方法返回与参数中的key_element关联的值。

异常:当指定的key_element为null时,该函数将引发NullPointerException。

以下程序说明了java.util.concurrent.ConcurrentHashMap.get()方法的用法:

示例1:该程序涉及将字符串值映射到整数键。

// Java Program Demonstrate get() 
// method of ConcurrentHashMap 
  
import java.util.concurrent.*; 
  
class GFG { 
    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, "Contribute"); 
  
        // Displaying the HashMap 
        System.out.println("The Mappings are: "); 
        System.out.println(chm); 
  
        // Display the value of 100 
        System.out.println("The Value associated to "
                           + "100 is : " + chm.get(100)); 
  
        // Getting the value of 103 
        System.out.println("The Value associated to "
                           + "103 is : " + chm.get(103)); 
    } 
}
输出:
The Mappings are: 
{100=Geeks, 101=for, 102=Geeks, 103=Contribute}
The Value associated to 100 is : Geeks
The Value associated to 103 is : Contribute

示例2:该程序涉及将整数值映射到字符串键。

// Java Program Demonstrate get() 
// method of ConcurrentHashMap 
  
import java.util.concurrent.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        ConcurrentHashMap<String, Integer> 
            chm = new ConcurrentHashMap<String, Integer>(); 
  
        chm.put("Geeks", 100); 
        chm.put("GFG", 10); 
        chm.put("GeeksforGeeks", 25); 
        chm.put("Contribute", 102); 
  
        // Displaying the HashMap 
        System.out.println("The Mappings are: "); 
        System.out.println(chm); 
  
        // Display the value of Geeks 
        System.out.println("The Value associated to "
                           + "Geeks is : " + chm.get("Geeks")); 
  
        // Getting the value of Contribute 
        System.out.println("The Value associated to "
                           + "Contribute is : " + chm.get("Contribute")); 
    } 
}
输出:
The Mappings are: 
{GeeksforGeeks=25, Geeks=100, GFG=10, Contribute=102}
The Value associated to Geeks is : 100
The Value associated to Contribute is : 102

参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#get()



相关用法


注:本文由纯净天空筛选整理自RICHIK BHATTACHARJEE大神的英文原创作品 ConcurrentHashMap get() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。