Java HashMap containsKey()方法

java.util.HashMap.containsKey() 方法用于检查特定键是否已映射到HashMap中。它使用key元素作为参数,如果该元素在映射中映射,则返回True。

1 语法

public boolean containsKey(Object key)

2 参数

key :在映射内检查其映射的键。

3 返回值

如果检测到键的存在,则该方法返回boolean true,否则返回false。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.HashMap.containsKey()方法的例子
 */
import java.util.*;

public class Demo {
    public static void main(String args[]) {

        // Creating an empty HashMap
        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();

        // Mapping string values to int keys
        hash_map.put(10, "Yiidian");
        hash_map.put(15, "4");
        hash_map.put(20, "Yiidian");
        hash_map.put(25, "Welcomes");
        hash_map.put(30, "You");

        // Displaying the HashMap
        System.out.println("Initial Mappings are: " + hash_map);

        // Checking for the key_element '20'
        System.out.println("Is the key '20' present? " +
                hash_map.containsKey(20));

        // Checking for the key_element '5'
        System.out.println("Is the key '5' present? " +
                hash_map.containsKey(5));
    }
}

输出结果为:

Initial Mappings are: {20=Yiidian, 25=Welcomes, 10=Yiidian, 30=You, 15=4}
Is the key '20' present? true
Is the key '5' present? false

热门文章

优秀文章