📜  Java中的 EnumMap containsKey() 方法

📅  最后修改于: 2022-05-13 01:54:26.878000             🧑  作者: Mango

Java中的 EnumMap containsKey() 方法

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

句法:

boolean containsKey(Object key)

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

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

下面的程序说明了 containsKey() 方法:
方案一:

// Java program to demonstrate 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 mp = new 
        EnumMap(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

方案二:

// Java program to demonstrate 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 mp = new 
        EnumMap(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