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


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


Java.util.EnumMap.containsKey(key)方法用于检查此映射中是否存在参数中提到的指定键。

用法:

boolean containsKey(Object key)

参数:该方法接受一个参数 key ,该参数 key 是要验证的 key 。


返回值:如果键在EnumMap中存在,则该方法返回true,否则返回false。

以下示例程序旨在说明containsKey()方法:
示例1:

// Java program to demonsrate containsKey() method 
import java.util.*; 
  
// An enum of gfg visitors is created 
public enum gfg_visitors { 
    India, 
    United_States, 
    China, 
    Japan, 
    Canada 
}; 
  
class Enum_map { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gfg_visitors, String> mp = new 
        EnumMap<gfg_visitors, String>(gfg_visitors.class); 
  
        // values are associated in mp 
        mp.put(gfg_visitors.India, "61.4%"); 
        mp.put(gfg_visitors.United_States, "18.4%"); 
        mp.put(gfg_visitors.China, "2.5%"); 
        mp.put(gfg_visitors.Japan, "1.1%"); 
        mp.put(gfg_visitors.Canada, "1.1%"); 
  
        // Check if map contains gfg visitor from United_States 
        boolean ans = mp.containsKey(gfg_visitors.United_States); 
  
        // Prints the result 
        System.out.println("gfg_visitors from United States: " + ans); 
    } 
}
输出:
gfg_visitors from United States: true

示例2:

// Java program to demonsrate containsKey() method 
import java.util.*; 
  
// An enum of gfg visitors is created 
public enum gfg_visitors { 
    India, 
    United_States, 
    China, 
    Japan, 
    Canada, 
    Russia 
}; 
  
class Enum_map { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gfg_visitors, String> mp = new 
        EnumMap<gfg_visitors, String>(gfg_visitors.class); 
  
        // values are associated in mp 
        mp.put(gfg_visitors.India, "61.4%"); 
        mp.put(gfg_visitors.United_States, "18.4%"); 
        mp.put(gfg_visitors.China, "2.5%"); 
        mp.put(gfg_visitors.Japan, "1.1%"); 
        mp.put(gfg_visitors.Canada, "1.1%"); 
  
        // check if map contains gfg visitor from Russia 
        boolean ans = mp.containsKey(gfg_visitors.Russia); 
  
        // prints the result 
        System.out.println("gfg_visitors from Russia: " + ans); 
    } 
}
输出:
gfg_visitors from Russia: false


相关用法


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