基于哈希表实现的键值对映射集合
HashMap 基于哈希表实现,通过 key 可以快速查找对应的 value。key 和 value 都可以为 null(但 key 只能有一个 null)。
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
// 创建 HashMap
Map<String, Integer> scores = new HashMap<>();
// 添加键值对
scores.put("张三", 85);
scores.put("李四", 90);
scores.put("王五", 78);
// 获取值
int zhangScore = scores.get("张三");
System.out.println("张三的成绩: " + zhangScore);
// 检查是否包含某个 key
boolean hasLi = scores.containsKey("李四"); // true
// 遍历 Map 的三种方式
System.out.println("方式1 - 遍历键:");
for (String name : scores.keySet()) {
System.out.println(name + ": " + scores.get(name));
}
System.out.println("方式2 - 遍历键值对:");
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 删除元素
scores.remove("王五");
System.out.println("删除后大小: " + scores.size());
}
}
1. 键值对存储:key 唯一,value 可以重复
2. 快速查找:通过 key 查找 value,O(1)
3. 无序:不保证插入顺序
4. 允许一个 null key 和多个 null value
Map map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("A", 3);
System.out.println(map.get("A"));