【Java】HashMap讲解
HashMap的核心原理
HashMap基于哈希表实现,采用数组+链表/红黑树结构存储键值对。
数据结果演进
- JDK 1.7及之前:仅使用数组+链表处理哈希冲突,链表过长时查询效率退化至O(n)。
- JDK 1.8+:引入红黑树优化,当链表长度≥8且数组容量≥64时,链表转为红黑树,将最差查询效率提升至O(log n)
关键机制详解
1. 哈希计算
通过key.hashCode()获取原始哈希值,再通过扰动函数(高16位异或)降低碰撞概率,最终通过(n-1) & hash确定数组下标。
2. 哈希冲突解决
- 链表法:冲突节点以链表形式存储,新元素插入链表尾部(JDK 1.7头插法,1.8改为尾插法)。
- 树化:链表长度超过阈值(默认8)且数组容量≥64时转为红黑树,节点数≤6时退化为链表。
3. 扩容机制
默认负载因子0.75,当元素数量超过容量*负载因子时触发扩容。新容量为原容量的2倍,所有节点重新散列。
基础操作
创建实例
Hashtable默认构造器的初始容量是11,负载因子0.75。可以在构造实例时指定初始容量和负载因子,如初始容量设置为0,会被自动修正为1。
import java.util.HashMap;
HashMap<String, Integer> hashmap = new HashMap();
HashMap<String, Integer> hashmap1 = new HashMap(12, 0.8f);
添加/修改元素
使用put(key, value)方法,键值均不可为null。
HashMap<String, Integer> hashmap= new HashMap();
// 添加元素
hashmap.put("Apple", 1);
System.out.println(hashmap); // {Apple=1}
// 修改元素
hashmap.put("Apple", 3);
System.out.println(hashmap); // {Apple=3}
获取元素
使用get(key)根据键查找值,若不存在返回null。
使用getOrDefault(key, defaultValue)根据键查找值,若存在则返回;若不存在键则返回默认值。
System.out.println(hashmap.get("Apple")); // 3
System.out.println(hashmap.getOrDefault("Orange", 5)); // 5
删除元素
使用remove(key)删除指定键的键值对。
hashmap.remove("Apple");
System.out.println(hashmap); // {}
获取键值对数量
使用size()获取键值对的数量。
hashmap.put("Apple", 1);
hashmap.put("Orange", 2);
hashmap.put("Banana", 3);
System.out.println(hashmap.size()); // 3
清空HashMap
使用clear()清空HashMap。
hashmap.clear();
System.out.println(hashmap); // {}
其他常用方法
键集合
通过keySet()获取所有键。
HashMap<String, Integer> hashmap= new HashMap();
hashmap.put("Apple", 1);
hashmap.put("Orange", 2);
hashmap.put("Banana", 3);
System.out.println(hashmap.keySet()); // [Apple, Orange, Banana]
键值对集合
使用entrySet()获取Entry对象集合。
HashMap<String, Integer> hashmap= new HashMap();
hashmap.put("Apple", 1);
hashmap.put("Orange", 2);
hashmap.put("Banana", 3);
System.out.println(hashmap.entrySet()); // [Apple=1, Orange=2, Banana=3]
检查键/值是否存在
通过containsKey(key)检查键是否存在。
通过containsValue(value)检查值是否存在。
HashMap<String, Integer> hashmap= new HashMap();
hashmap.put("Apple", 1);
hashmap.put("Orange", 2);
hashmap.put("Banana", 3);
System.out.println(hashmap.containsKey("Apple")); // true
System.out.println(hashmap.containsValue(5)); // false
浙公网安备 33010602011771号