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


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


java.util.concurrent.ConcurrentHashMap.containsKey()方法是Java中的内置函数,它接受参数并检查其是否为该映射中的键。

用法:

chm.containsKey(Object key_element)

参数:该方法接受对象类型的单个参数key_element,将检查该对象是否为键。


返回值:如果指定的key_element是此映射的键,则该方法返回true,否则返回false。

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

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

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

/* Java Program Demonstrate containsKey() 
   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"); 
  
        // Checking whether 105 is a key of the map 
        if (chm.containsKey(105)) { 
            System.out.println("105 is a key."); 
        } 
        else { 
            System.out.println("105 is not a key."); 
        } 
  
        // Checking whether 100 is a key of the map 
        if (chm.containsKey(100)) { 
            System.out.println("100 is a key."); 
        } 
        else { 
            System.out.println("100 is not a key."); 
        } 
    } 
}
输出:
105 is not a key.
100 is a key.

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

/* Java Program Demonstrate containsKey() 
   method of ConcurrentHashMap */
  
import java.util.concurrent.*; 
class ConcurrentHashMapDemo { 
    public static void main(String[] args) 
    { 
        ConcurrentHashMap<String, Integer> chm =  
                  new ConcurrentHashMap<String, Integer>(); 
        chm.put("Geeks", 120); 
        chm.put("for", 11); 
        chm.put("GeeksforGeeks", 15); 
        chm.put("Gfg", 50); 
        chm.put("GFG", 25); 
  
        // Checking whether GFG is a key of the map 
        if (chm.containsKey("GFG")) { 
            System.out.println("GFG is a key."); 
        } 
        else { 
            System.out.println("GFG is not a key."); 
        } 
  
        // Checking whether Geek is a key of the map 
        if (chm.containsKey("Geek")) { 
            System.out.println("Geek is a key."); 
        } 
        else { 
            System.out.println("Geek is not a key."); 
        } 
    } 
}
输出:
GFG is a key.
Geek is not a key.

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



相关用法


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