HashMap 基本概念
HashMap 是 Java 中基于哈希表的 Map 接口实现,用于存储键值对(Key-Value)。它允许 null 键和 null 值,并且不保证元素的顺序。HashMap 通过哈希函数计算键的哈希值,从而快速定位存储位置,实现高效的插入、删除和查找操作。
创建 HashMap
使用 HashMap
构造函数创建实例,可以指定初始容量和负载因子(可选)。
// 默认构造函数(初始容量16,负载因子0.75)
HashMap<String, Integer> map1 = new HashMap<>();
// 指定初始容量
HashMap<String, Integer> map2 = new HashMap<>(20);
// 指定初始容量和负载因子
HashMap<String, Integer> map3 = new HashMap<>(20, 0.8f);
常用方法
添加键值对
使用 put()
方法添加键值对。如果键已存在,则更新对应的值。
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
获取值
通过 get()
方法根据键获取值。若键不存在,返回 null
。
Integer value = map.get("apple"); // 返回 10
Integer unknown = map.get("grape"); // 返回 null
检查键或值是否存在
containsKey()
:检查键是否存在。containsValue()
:检查值是否存在。
boolean hasKey = map.containsKey("apple"); // true
boolean hasValue = map.containsValue(20); // true
删除键值对
remove(key)
:删除指定键的键值对。remove(key, value)
:仅当键和值都匹配时删除。
map.remove("banana"); // 删除键为 "banana" 的条目
map.remove("apple", 5); // 仅当 "apple" 对应值为5时删除
替换值
replace(key, newValue)
:替换指定键的值。replace(key, oldValue, newValue)
:仅当旧值匹配时替换。
map.replace("orange", 40); // 将 "orange" 的值改为40
map.replace("apple", 10, 15); // 仅当 "apple" 的值为10时改为15
遍历 HashMap
- 遍历键:使用
keySet()
。 - 遍历值:使用
values()
。 - 遍历键值对:使用
entrySet()
。
// 遍历键
for (String key : map.keySet()) {
System.out.println(key);
}
// 遍历值
for (Integer value : map.values()) {
System.out.println(value);
}
// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
其他实用方法
size()
:返回键值对数量。isEmpty()
:检查是否为空。clear()
:清空所有键值对。putAll()
:将另一个 Map 的所有键值对添加到当前 Map。
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
HashMap<String, Integer> anotherMap = new HashMap<>();
anotherMap.put("c", 3);
anotherMap.put("d", 4);
map.putAll(anotherMap); // 合并两个Map
性能注意事项
- 初始容量:根据预估数据量设置初始容量,避免频繁扩容。
- 负载因子:默认0.75,表示当填充程度达到75%时进行扩容。
- 线程安全:
HashMap
非线程安全,多线程环境下应使用ConcurrentHashMap
或Collections.synchronizedMap()
。
示例代码
以下是一个完整示例:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
System.out.println(map.get("apple")); // 输出10
System.out.println(map.containsKey("banana")); // 输出true
map.replace("banana", 30);
map.remove("apple");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}