How do you use a hashmap?
HashMap is a data structure in Java that is used to store mapping relationships between keys and values. Here are some common operations when using HashMap:
- Create a HashMap object:
HashMap<String, Integer> hashMap = new HashMap<>();
- Add key-value pair:
hashMap.put("key1", 1);
hashMap.put("key2", 2);
- Get value:
int value = hashMap.get("key1"); // 获取键"key1"对应的值
- Check if the key exists:
boolean containsKey = hashMap.containsKey("key1"); // 判断是否包含键"key1"
- Check if the value exists.
boolean containsValue = hashMap.containsValue(1); // 判断是否包含值1
- Remove key-value pair.
hashMap.remove("key2"); // 移除键"key2"对应的键值对
- Iterate through key-value pairs:
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
System.out.println(key + ": " + value);
}
Note: The keys in a HashMap are unique, if a key that is already existing is added, the new value will replace the old value.