1. HashMap概览
- HashMap类定义
HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>
HashMap继承了AbstractMap同时实现了Map接口,说明HashMap同样具有2对修改操作 3个遍历操作,5个查询操作。本文的主要大概也将围绕这10个操作来讲解HashMap
- Node类
在Map接口中,定义了一个Entry
interface Entry<K,V> {
K getKey();
V getValue();
V setValue(V value);
}
在HashMap中定义了静态内部类Node来表示HashMap中键值对的数据结构
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//key对应的hash值
final K key;//key是不可变的
V value;
Node<K,V> next;//链表指向的下一个Node,是为了解决Hash冲突
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;
}
}
- HashMap内部数据结构
HashMap内部的基础数据结构是数组+链表/红黑树实现。数组的实现好处是支持随机访问,根据下标查询的时间复杂是o(1)。
transient Node<K,V>[] table;
4.根据key的hash值确定Node在table数组中的下标
计算hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
通过table的length&hash值确定下标
i = (n - 1) & hash]
2. Map接口详解
1. V put(K,V)
思路讲解
- 通过key计算hash值,并通过hash值确认在table数组中的位置i
- 如果table[i]==null,根据key value创建Node对象赋值给table[i]
- 如果table[i]!=null,通过next遍历table[i]上的Node。如果key相等替换Node,如果不相等,创建Node添加到链表最后面(这里不讲红黑树)
//V !!!!注意 返回的是原先的值
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
//如果table数组还没有初始化,通过resize()初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//通过hash值定位到数组的下标,如果该位置上没有数据,创建node并赋值到该位置上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果下标的位置上有数据
Node<K,V> e; K k;
//如果位置上的hash值和key与要插入的Node相等,把节点赋值给e。后面会替换e的value
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);
else {//还是链表的形式存储
//遍历当前数组上的Node的链表
for (int binCount = 0; ; ++binCount) {
//遍历到最后一个Node
if ((e = p.next) == null) {
//新建Node指向链表最后面
p.next = newNode(hash, key, value, null);
//如果链表的长度超过了8 将链表红黑树化
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果遍历的过程发现了key相同的
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//条件不满足p指针往后移动
p = e;
}
}
//对于已经存在的key替换value的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//afterNodeAccess(e)!!!注意这个方法LinkedHashMap会用到,在HashMap中是空实现
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果插入后数组大小超过设置的值 需要对数组扩容
if (++size > threshold)
resize();
//hashMap是空实现
afterNodeInsertion(evict);
return null;
}
afterNodeAccess只在put后才会调整
红黑树化 这里暂时没看懂
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//扩容
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
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);//双链表红黑树化
}
}
2. V get(Object key)
思路讲解
- 通过key计算hash值,通过hash值获取数组的下标i
- 若果table[i]==null,返回null
- 如果table[i]!=null
- 判断table[i]的hash值和key是否和要查询的相等,如果相等返回。
- 如果不相等,如果节点是红黑树,通过红黑树遍历,如果是链表通过链表遍历。
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);
}
}
return null;
}
3. int size()
public int size() {
return size;
}
4. boolean isEmpty()
public boolean isEmpty() {
return size == 0;
}
5. Set
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();//主要是通过迭代器来实现遍历
}
}
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // 遍历数组找到第一个不为null的Node
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {//先遍历链表,如果链表还有数据
do {} while (index < t.length && (next = t[index++]) == null);//再遍历数组
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}