新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

hashmap判断key相等的有哪些方法,hashmap key是否存在

发布时间:2024-06-03 17:37:11

hashmap判断key相等的有哪些方法

在Java中,可使用HashMap的containsKey()方法来判断是否是存在指定的key。该方法会返回一个boolean值,表示是否是存在指定的key。如果存在,则返回true;如果不存在,则返回false。示例以下:

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");

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");
}

在上面的示例中,我们先创建了一个HashMap对象,并向其添加了两个key-value对。然后使用containsKey()方法判断是否是存在key为 “key1” 的键,终究输出相应的结果。