hashmap如何判断key存不存在

640
2024/3/15 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元/月。点击查看>>

推荐阅读: hashmap链表的初始容量如何设置