hashmap

hashmap如何判断key存不存在

小亿
283
2024-02-19 16:04:30
栏目: 编程语言
开发者专用服务器限时活动,0元免费领! 查看>>

在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中,并输出相应的提示信息。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:python怎么判断文件存不存在

1
看了该问题的人还看了