温馨提示×

hashmap如何判断key存不存在

小亿
116
2024-02-19 16:04:30
栏目: 编程语言

在HashMap中,可以使用containsKey()方法来判断指定的key是否存在于HashMap中。如果存在,则该方法返回true,否则返回false。示例如下:

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("key1", 1);
hashMap.put("key2", 2);

if (hashMap.containsKey("key1")) {
    System.out.println("Key 'key1' exists in the HashMap");
} else {
    System.out.println("Key 'key1' does not exist in the HashMap");
}

if (hashMap.containsKey("key3")) {
    System.out.println("Key 'key3' exists in the HashMap");
} else {
    System.out.println("Key 'key3' does not exist in the HashMap");
}

上面的示例中,首先创建了一个HashMap对象,并向其中添加了两个键值对。然后使用containsKey()方法来判断指定的key是否存在于HashMap中,并输出相应的提示信息。

0