import java.util.HashMap;
public class ContainsKeyExample {
public static void main(String[] args) {
// 创建一个HashMap实例
HashMap<String, Integer> map = new HashMap<>();
// 向HashMap中添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 检查HashMap中是否包含指定的键
String keyToCheck = "banana";
if (map.containsKey(keyToCheck)) {
System.out.println("HashMap contains the key: " + keyToCheck);
} else {
System.out.println("HashMap does not contain the key: " + keyToCheck);
}
// 检查HashMap中是否包含不存在的键
String nonExistentKey = "grape";
if (map.containsKey(nonExistentKey)) {
System.out.println("HashMap contains the key: " + nonExistentKey);
} else {
System.out.println("HashMap does not contain the key: " + nonExistentKey);
}
}
}
HashMap<String, Integer> map = new HashMap<>();:创建一个HashMap对象,键是String类型,值是Integer类型。map.put("apple", 1);:向HashMap中添加键值对。map.containsKey(keyToCheck):检查HashMap中是否包含指定的键。如果包含,则返回true,否则返回false。if (map.containsKey(keyToCheck)) { ... }:使用if语句来判断HashMap中是否包含某个键,并根据结果输出相应的信息。这个示例代码展示了如何使用containsKey方法来检查HashMap中是否存在某个键。
上一篇:java集合类
下一篇:java keystore
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站