hashmap如何判断key存不存在
在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中,并输出相应的提示信息。
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。