一、HashMap
基于数组和链表实现的HashMap,当链表数据过多时,会转为红黑树提高查询效率。
实现采用了多种数据结构,所以HashMap在增删改查上的效率都很高,不考了哈希冲突时间复杂度可以达到O(1)
二、源码分析
2.1 继承结构和层次
实现了Map接口,克隆接口和序列化接口
2.2 HashMap属性
/**
* 默认初始容量
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
*默认最大容量
*/
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;
/**
* 桶中数据采用树存储时,最小的容量
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 存储元素的哈希表数组
*/
transient Node<K,V>[] table;
/**
* HashMap大小
*/
transient int size;
/**
* 修改次数
*/
transient int modCount;
/**
* 容量临界值 (capacity * load factor).
*/
int threshold;
/**
* 负载因子
*/
final float loadFactor;
Node节点代码如下,可以看出是一个链表
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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
2.3 构造方法
无参构造方法
将负载因子loadFactor设置为默认负载因子0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
带容量构造方法
public HashMap(int initialCapacity) {
//调用了带容量和默认负载因子的构造方法
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
带容量和负载因子的构造方法
根据传入参数赋值给threshold 和 loadFactory
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
map参数构造方法
public HashMap(Map<? extends K, ? extends V> m) {
//负载因子使用默认值
this.loadFactor = DEFAULT_LOAD_FACTOR;
//存入数据
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//获取传入map大小
int s = m.size();
if (s > 0) {
//判断table是否初始化
if (table == null) { // pre-size
//长度=容量*负载因子,此处求容量,+1.0F防止后面类型转为int时容量小了
float ft = ((float)s / loadFactor) + 1.0F;
//容量小于上线则使用计算出的容量
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
//初始化临界值,
if (t > threshold)
//获得比入参数大的2的高次幂
threshold = tableSizeFor(t);
}
//table已经初始化了,进行扩容
else if (s > threshold)
resize();
//扩容后吧map的数组转如hashmap中
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
2.4 常用方法
2.4.1 新增
会涉及到hash计算,先看下hash值的计算
static final int hash(Object key) {
int h;
//key的hash值赋给h,计算h与h移位的异或,减少hash冲突
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
以及resize方法,调整table数组大小
final Node<K,V>[] resize() {
//未resize前的table作为oldTab
Node<K,V>[] oldTab = table;
//获得oldTab的长度oldCap
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//获得未resize前的临界值threshold作为oldThr
int oldThr = threshold;
//初始化新的长度和临界值
int newCap, newThr = 0;
//已经初始化过了
if (oldCap > 0) {
//如果大于最大值
if (oldCap >= MAXIMUM_CAPACITY) {
//临界值设为最大值
threshold = Integer.MAX_VALUE;
//返回旧table,无扩容
return oldTab;
}
//扩容两倍且小于最大容量 && 旧长度大于16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//临界值扩大两倍
newThr = oldThr << 1; // double threshold
}
//如果临界值oldThr>0,说明已经被初始化了,但是无数据,
else if (oldThr > 0) // initial capacity was placed in threshold
//设置新的临界值同旧临界值
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//之前未初始化,初始化为默认值
newCap = DEFAULT_INITIAL_CAPACITY; //16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
}
//如果扩容临界值还为0
if (newThr == 0) {
//根据容量*负载因子计算临界值
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//赋值给新的临界值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//初始化table
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//旧数据存入
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
//返回扩容后的table
return newTab;
}
新增的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) {
//定义哈希数组,哈希桶,hashmap长度,数组下标
Node<K,V>[] tab; Node<K,V> p; int n, i;
//未初始化则进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算当前哈希桶位置是否有值,为空则直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//产生哈希冲突
else {
Node<K,V> e; K k;
//如果当前节点的hash值和key值与传入的hash值和key值一致,则更新数据
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//在后面会用到e值来更新
e = p;
else if (p instanceof TreeNode)
//如果当前节点已属于TreeNode,则在树中添加
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//遍历链表
for (int binCount = 0; ; ++binCount) {
//如果找完都没有重复,在尾部进行添加
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//判断是否要转换为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果链表中有重复的key,根据后面更新e节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果e不为null,存在重复key,用插入值替代旧值,返回旧值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//此处表明无重复key,修改次数+1
++modCount;
//元素个数+1,并判断是否大于临界值,是否需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2.4.2 删除
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//校检table不为空且在table对应的数组下标不为null,p是数组下标的节点
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果数组下标的节点正好是当前要删除的节点,把p赋值给临时节点node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//删除的节点在树上,查找红黑树
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//链表节点,遍历链表节点
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//判断node是否为空,且值是否相等
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
//移除树的节点
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
//直接覆盖索引位置
tab[index] = node.next;
else
//通过链表移除node
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
2.4.3 修改
修改也是put操作,将旧值覆盖,刚刚也已经分析了
2.4.4 查询
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//同之前一样
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果是头结点,则直接返回头结点
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//如果不是头结点
if ((e = first.next) != null) {
//树结构则查找红黑树
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//链表结构,遍历链表查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//未找到,返回null
return null;
}
先分析基本方法,关于红黑树的操作比较复杂,不在这里展开。后面分析到红黑树了再说
三、总结
- HashMap使用hashCode,可以定位到他应该放置哈希桶的位置,如果产生了hash冲突,在改为链表形式或红黑树形式继续存储元素
- 结合了数组和链表的优势
- 遍历时可以通过entry来取HashMap的键值对数据