HashMapは、keyが存在するかどうかを判断する方法は何ですか。

HashMap内では、指定のキーが存在するかどうかをcontainsKey()メソッドを使用して判断することができます。キーが存在する場合は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オブジェクトが作成され、2つのキーと値が追加されました。その後、containsKey()メソッドを使用して指定されたキーがHashMapに存在するかどうかを判断し、適切なメッセージを出力します。

bannerAds