Java 集合系列10: HashMap 详细介绍(源码解析)与使用示例

HashMap 是 Java 集合框架中最重要且最常用的实现类之一,它提供了基于键值对(Key-Value)的高效存储与检索功能。无论是在日常业务开发还是高性能应用中,HashMap 都扮演着核心角色。本文将深入剖析 HashMap 的实现原理、关键源码细节,并通过实际示例展示最佳使用实践,帮助开发者全面掌握这个强大工具。

目录#

  1. HashMap 概述
    • 基本概念与特性
    • 类继承关系
  2. 核心实现原理
    • 内部数据结构
    • 哈希冲突解决
    • Java 8 的优化(红黑树)
  3. 关键源码解析
    • 核心属性分析
    • put 方法详细流程
    • get 方法执行机制
    • resize 扩容原理
    • 树化与反树化过程
  4. 使用示例
    • 基础操作示例
    • 自定义对象作为键
    • Lambda 表达式应用
  5. 性能考虑
    • 负载因子与初始化容量
    • 时间复杂度分析
    • 线程安全方案
  6. 常见问题与最佳实践
  7. 总结
  8. 参考资料

1. HashMap 概述#

基本概念与特性#

  • 键值对存储:以<Key, Value>形式存储数据
  • 不允许重复键:相同键的新值会覆盖旧值
  • 允许null键和null值:最多一个null键
  • 无序集合:迭代顺序不固定(Java 8后改为按桶顺序)
  • 非线程安全:多线程场景需要外部同步

类继承关系#

java.lang.Object
  ↳ java.util.AbstractMap<K,V>
      ↳ java.util.HashMap<K,V>

实现的主要接口:

  • Map<K,V>
  • Cloneable
  • Serializable

2. 核心实现原理#

内部数据结构(Java 8之前后对比)#

+----------------+
|     HashMap    |
+----------------+
|   Node<K,V>[]  |
|   table       →+----→ +----------------+
+----------------+      |   Node<K,V>   |
                        | - hash: int   |
                        | - key: K      |
                        | - value: V    |
                        | - next: Node →+---→ 链表结构
                        +----------------+
 
(Java 8优化:链表长度>8时转红黑树)
                        +----------------+
                        | TreeNode<K,V> | → 红黑树节点
                        +----------------+

哈希冲突解决#

当两个不同的键计算出相同的索引位置时发生哈希冲突,HashMap 采用两种方式解决:

  1. 链地址法(Separate Chaining)
    • 同一桶位存储链表结构
  2. 红黑树优化(Java 8+)
    • 当链表长度超过阈值(8) 时转为红黑树
    • 树节点数小于阈值(6) 时转回链表

Java 8 的优化总结#

优化点Java 7及之前Java 8+
冲突处理纯链表链表+红黑树
扩容方式头插法(可能死循环)尾插法(安全)
节点结构EntryNode/TreeNode
性能稳定性O(n)最坏情况O(log n)最坏情况

3. 关键源码解析#

核心属性分析#

public class HashMap<K,V> extends AbstractMap<K,V> 
    implements Map<K,V>, Cloneable, Serializable {
    
    // 默认初始化容量 (2^4)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    
    // 最大容量 (2^30)
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
    // 默认负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    // 树化阈值(链表→树)
    static final int TREEIFY_THRESHOLD = 8;
    
    // 反树化阈值(树→链表)
    static final int UNTREEIFY_THRESHOLD = 6;
    
    // 哈希表(桶数组)
    transient Node<K,V>[] table;
    
    // 实际存储的键值对数量
    transient int size;
    
    // 扩容阈值 = 容量 × 负载因子
    int threshold;
    
    // 负载因子
    final float loadFactor;
}

put 方法执行流程#

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
 
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 1. 第一次put时初始化table
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    
    // 2. 计算桶位索引:(n-1) & hash
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null); // 无冲突直接插入
    else {
        Node<K,V> e; K k;
        // 3. 桶位已存在节点
        if (p.hash == hash && 
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p; // 第一个节点就是目标
        else if (p instanceof TreeNode) // 红黑树处理
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 4. 遍历链表
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null); // 尾部插入
                    // 5. 检查树化:binCount从0开始计数
                    if (binCount >= TREEIFY_THRESHOLD - 1) 
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && 
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break; // 找到相同键
                p = e;
            }
        }
        
        // 6. 替换已有键的值
        if (e != null) {
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue; // 返回旧值
        }
    }
    ++modCount;
    // 7. 超过阈值则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

get 方法源码简析#

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
 
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 1. 表非空且桶位非空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 2. 检查桶位第一个节点
        if (first.hash == hash && 
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            // 3. 如果是树节点,走树查找
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 4. 遍历链表查找
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

resize 扩容机制#

  1. 扩容触发条件:size > threshold
  2. 新容量计算:当前容量 × 2
  3. 数据迁移优化
    • Java 8前:链表元素全部重新哈希
    • Java 8优化:保持原有顺序,利用高位区分
      // 扩容后索引 = 原始位置 OR 原始位置+旧容量
      if ((e.hash & oldCap) == 0) {
          // 低位链表:保持原索引
      } else {
          // 高位链表:索引=原索引+oldCap
      }

树化与反树化#

  • 树化条件(同时满足):
    1. 链表长度 ≥ TREEIFY_THRESHOLD(8)
    2. 桶数组长度 ≥ MIN_TREEIFY_CAPACITY(64)
  • TreeNode 结构
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父节点
        TreeNode<K,V> left;    // 左子树
        TreeNode<K,V> right;   // 右子树
        TreeNode<K,V> prev;    // 前一个节点(保持链表访问)
        boolean red;           // 颜色标识
    }

4. 使用示例#

基础操作示例#

import java.util.HashMap;
 
public class HashMapBasicDemo {
    public static void main(String[] args) {
        // 创建HashMap并初始化容量(避免频繁扩容)
        HashMap<String, Integer> scores = new HashMap<>(16);
        
        // 添加元素
        scores.put("Alice", 95);
        scores.put("Bob", 87);
        scores.put("Charlie", 92);
        scores.put(null, 0);  // 允许null键
        
        // 获取元素
        System.out.println("Bob's score: " + scores.get("Bob")); // 87
        
        // 检查Key是否存在
        System.out.println("Contains key 'Alice'? " + 
                            scores.containsKey("Alice")); // true
        
        // 遍历所有键值对 (Java 8+)
        scores.forEach((name, score) -> 
            System.out.println(name + ": " + score)
        );
        
        // 更新值(Bob重新考试)
        scores.computeIfPresent("Bob", (k, v) -> v + 5); // +5分
        System.out.println("Bob's new score: " + scores.get("Bob")); // 92
    }
}

自定义对象作为键#

class Student {
    private final int id;
    private final String name;
    
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    // 必须重写equals和hashCode
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return id == student.id && name.equals(student.name);
    }
    
    @Override
    public int hashCode() {
        return 31 * id + name.hashCode(); // 推荐计算方法
    }
}
 
public class CustomKeyDemo {
    public static void main(String[] args) {
        HashMap<Student, String> courseMap = new HashMap<>();
        
        Student alice = new Student(101, "Alice");
        courseMap.put(alice, "Computer Science");
        
        // 使用逻辑相等的Key检索
        Student sameAlice = new Student(101, "Alice");
        System.out.println("Alice's course: " + courseMap.get(sameAlice)); // 正确返回
    }
}

Java 8 新特性应用#

HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Apple", 50);
inventory.put("Banana", 30);
 
// 键不存在时初始化
inventory.putIfAbsent("Orange", 0);  // Orange不存在才加入
 
// 合并新值
inventory.merge("Apple", 10, Integer::sum); // Apple=60
 
// 删除元素新方式
inventory.remove("Banana", 20); // 仅在值为20时删除(实际30,不删除)
 
// 流操作过滤数据
inventory.entrySet().stream()
    .filter(entry -> entry.getValue() > 40)
    .forEach(entry -> System.out.println(entry.getKey()));

5. 性能考虑#

负载因子(Load Factor)与初始化容量#

  • 0.75负载因子是时间和空间成本的最佳平衡:

    • 值过小:空间浪费
    • 值过大:哈希冲突增加
  • 初始化容量公式:

    int initialCapacity = (int) (expectedSize / loadFactor) + 1;

时间复杂度分析#

操作平均情况最坏情况(Java 7)最坏情况(Java 8)
get()O(1)O(n)O(log n)
put()O(1)O(n)O(log n)
remove()O(1)O(n)O(log n)
contains()O(1)O(n)O(log n)

线程安全替代方案#

  1. Collections.synchronizedMap
    Map<String, Object> safeMap = 
        Collections.synchronizedMap(new HashMap<>());
  2. ConcurrentHashMap(推荐)
    ConcurrentHashMap<String, Integer> concurrentMap = 
        new ConcurrentHashMap<>();

6. 常见问题与最佳实践#

高频使用问题#

  1. HashMap 为什么线程不安全?

    • 同时扩容导致链表成环(Java 7)
    • 多线程put导致数据覆盖
  2. 为什么需要重写equals和hashCode?

    • hashCode:决定元素桶位位置
    • equals:键冲突时比较对象内容
    • 不重写会导致逻辑相等的键被放在不同桶位
  3. 为什么选择红黑树而不是AVL树?

    • 红黑树牺牲部分平衡性换取更高插入/删除性能
    • 平均查找效率接近AVL,维护代价更低

最佳实践#

  1. 正确重写hashCode()方法:

    • 使用Objects.hash(keyFields...)
    • 不同对象的哈希码尽可能分散
  2. 预分配初始容量:

    // 预计存储500个元素
    new HashMap<>(700); // 500/0.75 ≈ 666 +缓冲
  3. 避免在迭代过程中修改结构:

    • 使用Iterator.remove()删除元素
    • 或使用ConcurrentHashMap
  4. Java 8 优先使用新API:

    // 避免空指针
    map.getOrDefault(key, defaultValue);
     
    // 原子性更新
    map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);

7. 总结#

HashMap 作为 Java 集合框架的核心成员,通过巧妙的数组+链表+红黑树数据结构实现了高效的键值存储与检索。Java 8的优化解决了哈希碰撞导致的性能退化问题,使HashMap在大多数场景下都能保持O(1)的优秀时间复杂度。开发者在日常使用中需要注意:

  1. 正确重写键对象的hashCode()和equals()
  2. 预估初始容量以减少扩容开销
  3. 理解并发限制并选用线程安全替代方案
  4. 掌握Java 8新增的方法式API

通过本文的系统解析和实践示例,相信您已对HashMap有了更深入的理解!


参考资料#

  1. Oracle Java 17 HashMap Documentation
  2. Java 源码:OpenJDK 17 HashMap
  3. Bloch, J. Effective Java (3rd ed.). Addison-Wesley, 2018. (Chapters 11)
  4. Baeldung: Guide to Java HashMap
  5. Red-Black Tree Visualization