目录
1. 基本概述
HashMap是Java中最常用的集合类之一,它实现了Map接口,提供了键值对的存储方式。在JDK 1.8中,HashMap的实现采用了数组+链表+红黑树的数据结构,相比于JDK 1.7的数组+链表结构,在性能上有了显著提升。
1.1 主要特点
- 非线程安全
- 允许null键和null值
- 不保证元素顺序
- 初始容量和负载因子影响性能
2. 核心数据结构
2.1 整体结构图
2.2 数据结构定义
// 基本节点类
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 哈希值
final K key; // 键
V value; // 值
Node<K,V> next; // 下一个节点
// 构造函数
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
// 红黑树节点类
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // 父节点
TreeNode<K,V> left; // 左子节点
TreeNode<K,V> right;