创建HashMap
// 默认构造:初始容量16,负载因子0.75 HashMap<String, Integer> map = new HashMap<>(); // 指定初始容量 HashMap<String, Integer> mapWithCapacity = new HashMap<>(32); // 通过其他Map创建 HashMap<String, Integer> anotherMap = new HashMap<>(map);添加和获取元素
使用put()方法添加键值对,如果键已存在则会覆盖原有值并返回旧值
通过get()方法根据键获取对应的值
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 15);
Integer value = map.get("apple"); // 返回10
Integer notFound = map.get("grape"); // 返回null
删除和判断元素
map.remove("banana"); // 删除键为"banana"的映射
boolean exists = map.containsKey("apple"); // 检查键是否存在
核心特性键值对规则
1、键必须是唯一的,不允许重复
2、值可以重复
3、允许一个null键和多个null值
性能特点
1、基于哈希表实现,理想情况下get和put操作的时间复杂度为O(1)
2、无序存储,不保证元素的插入或访问顺序
3、非线程安全,多线程环境下需要外部同步
遍历方式
遍历所有键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
遍历所有键
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
遍历所有值
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
注意事项1、线程安全
HashMap是非线程安全的,如果需要在多线程环境中使用,可以使用:
Collections.synchronizedMap(new HashMap<>())
ConcurrentHashMap(推荐)
2、哈希冲突处理
当发生哈希冲突时,HashMap会使用链表或红黑树来存储冲突的元素
3、扩容机制
当元素数量超过容量乘以负载因子(默认16×0.75=12)时,HashMap会自动扩容为原数组容量的2倍
HashMap提供了高效的键值对存储和检索功能,是Java集合框架中最常用的数据结构之一。
发表评论