概述
本文主要分析HashMap类的源码
HashMap继承结构
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
HashMap继承结构图
可以看到:
1、实现了 Map 接口,拥有一组map的通用操作
2、实现了 Cloneable 接口,可进行拷贝,需要注意的是 hashmap 是浅拷贝,修改拷贝对象对源对象会产生影响
3、实现了 Serializable 接口,实现了序列化,可保存于本地
HashMap的数据结构
数组 + 单向链表
HashMap的成员变量
/**
* The default initial capacity - MUST be a power of two.
* 默认初始容量
*/
static final int DEFAULT_INITIAL_CAPACITY = 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;
/**
* The load factor used when none specified in constructor.
* 默认负载因子,用来指示元素个数占整体容量的比例,当元素达到这个比例的时候,就准备扩容了
* 为什么加载因子是0.75?【经常被问到的面试题】
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The table, resized as necessary. Length MUST Always be a power of two.
* 用来存储键值对的Entry数组
*/
transient Entry<K,V>[] table;
/**
* The number of key-value mappings contained in this map.
* 实际的元素个数
*/
transient int size;
/**
* The next size value at which to resize (capacity * load factor).
* 阈值 = capacity(容量)* loadFactor(负载因子。这个值是当前已占用数组长度的最大值。size 超过这个值就重新 resize(扩容),
* 扩容后的 HashMap 容量是之前容量的两倍。默认的临界值是12 = 16 * 0.75
*/
int threshold;
/**
* The load factor for the hash table.
* 哈希表的负载因子,默认是0.75f
*/
final float loadFactor;
/**
* 每次扩容和更改 map 结构的计数器
*/
transient int modCount;
Entry必须要介绍一下,看源码
static class Entry<K,V> implements Map.Entry<K,V> {
fina