📅  最后修改于: 2023-12-03 15:15:56.144000             🧑  作者: Mango
In Java, HashMap
is a class that implements the Map
interface, which represents a collection of objects that are mapped to keys. HashMap
uses a hash table to store the objects and their keys.
The containsKey()
method in HashMap
is used to check if a particular key is present in the hash table. This method returns a boolean value of true
if the specified key is present, and false
otherwise.
public boolean containsKey(Object key)
Here, the key
parameter is the key whose presence in the HashMap
is to be tested.
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> marks = new HashMap<>();
// Adding marks of students
marks.put("Alice", 90);
marks.put("Bob", 85);
marks.put("Charlie", 95);
marks.put("Dave", 80);
// Checking if a key is present
boolean isPresent = marks.containsKey("Alice");
System.out.println("Is Alice present? " + isPresent);
// Checking if a key is absent
isPresent = marks.containsKey("Eve");
System.out.println("Is Eve present? " + isPresent);
}
}
Output:
Is Alice present? true
Is Eve present? false
In the above example, a HashMap
named marks
is created to store the marks of various students. The containsKey()
method is used to check if the key "Alice"
is present in the HashMap
. Since "Alice"
is present, the output is true
. Similarly, the presence of key "Eve"
is checked, which is absent, so the output is false
.