简介
HashMap的key,value都可以为null;是由数组+链表实现的;无序的,线程不安全;HashMap对于手机端而言,对内存的占用比较大;某些情况下,可以用ArrayMap,SparseMap替代;
插入操作put(),putAll()
put()方法
key是唯一的,同一个key只能存在一个,再次put()会改变原来的值;
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal 方法主要做几件事,1)tab为null,调用resize()方法,确定容量,并创建数组;2)根据n-1 & hash 获取的值作为index,如果数组中index对应的值为null,直接将该节点存入数组中;3)数组中存在当前index对应的节点,判断是否存在key对应的节点;4)存在key对应的节点,返回oldValue,否则返回null;
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 确定容量,并创建数组;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//2 根据n-1 & hash 获取的值作为index,如果数组中index对应的值为null,直接将该节点存入数组中;
if ((p = tab[i = (n - 1) & hash]) == null)
//不同的类,调用各自的newNode()方法;
tab[i] = newNode(hash, key, value, null);
//3:数组中存在当前index对应的节点
else {
Node<K,V> e; K k;
//3.1 index对应的节点的key和当前key相同
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);
//3.2 不相同的话,遍历单链表,如果链表中存在节点的key和当前的key相等,返回对应的节点;不存在,在单链表插入一个新节点;
else {
for (int binCount = 0; ; ++binCount) {
//单链表中不存在当前key对应的节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//3.3 优化查询效率,避免效率低下;
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 判断节点e的key和当前key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//4:存在key对应的节点,改变其的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
//空方法,具体是实现在LinkedHashMap
afterNodeInsertion(evict);
return null;
}
resize()方法,主要做两件事:1)如果oldCap = 0,则确定新的长度;否则将长度增加两倍;创建新的数组;2)原数组不为null时,将原数组中的元素,拷贝到新数组中,并将新数组返回;
final Node<K,V>[] resize() {
....
//1)如果oldCap = 0,则确定新的长度;否则将长度增加两倍;创建新的数组
.....
//2:原数组不为null时,将原数组中的元素,拷贝到新数组中;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果当前index只对应一个元素,直接将其存入数组中;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果是TreeNode类型的
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;
}
}
}
}
}
return newTab;
}
再看下 treeifyBin()方法;1)如果当前tab数组太小,调用reset()扩容,并且可能的话减短单链表的长度,避免查询的时候,效率低下;2)先将单链表转换为双向链表,最后转换为红黑树结构;
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//当table的length不满足一定大小时;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//找到当前hash值对应的index的节点;
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
//do while将单链表转为双向链表;hd是header,t1是tail;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
//转换成红黑树
hd.treeify(tab);
}
}
replacementTreeNode()方法,将Node节点转换为TreeNode节点,TreeNode是用链表实现的树结构(红黑树);
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
看下TreeNode类,
static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
treeify():
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//this代表调用对象hd;从链表头往后遍历链表,将结构改为红黑树;主要操作时节点的插入;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
//将表头x赋值给root;
root = x;
}
//从treeifyBin方法可以知道,hash都相等;
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
//从根节点遍历树
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}
再看下moveRootToFront()方法,确保树的根节点是table对应index的值;
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
if (root != first) {
Node<K,V> rn;
tab[index] = root;
TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
最后看下 split():可能的话,分割链表;提高查询效率;
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
//遍历链表,可能的话讲链表转换为两个双向链表;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
//满足条件,转换为一个新链表
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
//否则为另一个链表;
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
//链表长度小于7;返回一个单链表;并将头结点放入table数组对应的index位置
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
//否则返回一个二叉树,并将头结点放入table数组对应的index位置;
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
untreeify()方法,返回一个单链表,非树结构
final Node<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
putAll() 插入一个Map,具体操作和put()方法基本一致;
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//数组table为null,设置容量等;不为nul,确定是否需要扩容;
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
//遍历,挨个插入;
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);
}
}
}
到此,put()方法分析完了;接下来看下get()方法;
get()方法
存在当前的key对应的节点,返回对一个的值,否则返回null;
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
执行getNode()方法获取当前key对应的节点,主要分为以下几种情况:
1)table 为空或者table中对应index的元素为null;
2) table 中存在对应index的元素;
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//table数组不为空,并且对应下标(由(n - 1) & hash得到)的元素不为null;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//index对应的元素的key和当前的key相同
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);
//遍历index对应的单链表,找到对应节点
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
看下getTreeNode()方法,数的遍历,找到对应的节点;
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
replace():
主要还是调用getNode()方法根据key找到对应节点e,如果e不为null,重新赋值value;否则返回null;
@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
remove()
如果存在key对应的节点,返回该节点对应的value,否则返回null;
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
removeNode():如果存在key对应的节点,返回该节点,否则返回null;
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不为空,length大于0;并且由key对应hash按照规则得到的index对应节点p不为null;
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节点是否为目标节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//不是的话,判断p.nex是否为null;
else if ((e = p.next) != null) {
//如果是TreeNode实例,遍历红黑树
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);
}
}
//如果存在
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);
//如果是数组index对应的节点,将该index对应节点置为null;
else if (node == p)
tab[index] = node.next;
//将p节点的next指向node节点的下一个节点(无论是否存在)
else
p.next = node.next;
++modCount;
--size;
//空方法,由子类具体实现;
afterNodeRemoval(node);
return node;
}
}
return null;
}
比较
HashMap的key,value都可以为null,线程不安全,是由数组+链表实现的;无序的;
HashTable用法基本和HashMap一致,
不同点:HashTable线程安全;value不可以为null;put()方法table中对应index不为null,将元素插在单链表链头,和HashMap不同;
ConcurrentHashMap用法基本和HashMap一致,也是线程安全的,比Hashtable效率高;ConcurrentHashMap将数据分为多个segment,默认16个(concurrency level),然后每次操作对一个segment加锁,避免多线程锁得几率,提高并发效率。
总结
put():效率比较低,1)要扩容,重新插入原来的元素;2)table中对应index不为null,将元素插在单链表链尾;
get(),remove(),replace():效率比较高;hash(key)&(length-1)得到数组table的index,判断index对应的节点是否需要找的;不是的话,然后就根据单链表,遍历循环找到key对应的节点,在进行相关的操作;
如有问题,请多指教,谢谢!