
HashMap (桶位数组 + 链表/红黑树 、线程不安全)(Java1.8以前 桶位数组+链表)
HashMap<K, V> 根据 K 的HashCode 来存储对应 V 大多数情况可以直接定位到它的 V 底层为哈希表访问时间复杂度为O(1) 但是遍历顺序却不确定 不是有序的(存储位置与插入时间无关) HashMap最多只允许一条记录的键 为 null ,允许多条记录的值为null。当出现Hash冲突时(即计算出的 HashCode 一样时)会使用拉链法将冲突的值加到链表头(如果链表时 尾部插入需要遍历找到尾部的位置时间复杂度为 O (n) 头部插入时间复杂度为 O(1) )

HashMap是线程不安全的当有多个线程进行同时写HashMap 可能导致数据不一样。如果需要具有线程安全的推荐使用ConcurrentHashMap(分段式锁)
源码解析:
初始:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 初始值为16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;// 最大值为 1 << 30
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;// 负载因子
// threshold :扩容的阈值 等于 capacity * loadFactor
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
// hash冲突默认采用单链表进行存储 当单链表的节点大于8时会转换成红黑树
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
// 当红黑树中节点少于6时会转换成单链表
/**
*

本文深入解析了Java集合框架中的HashMap,详细介绍了HashMap的数据结构、线程不安全问题及其扩容机制。同时对比了ConcurrentHashMap的线程安全实现,以及HashTable的全表锁策略。还提及了TreeMap的排序特性和LinkedHashMap的插入顺序记录功能。
最低0.47元/天 解锁文章
1083

被折叠的 条评论
为什么被折叠?



