當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。