一、数据结构
1、数组结构: 存储区间连续、内存占用严重、空间复杂度大
优点:随机读取和修改效率高,原因是数组是连续的(随机访问性强,查找速度快)
缺点:插入和删除数据效率低,因插入数据,这个位置后面的数据在内存中都要往后移动,且大小固定不易动态扩展。
2、链表结构:存储区间离散、占用内存宽松、空间复杂度小;
优点:插入删除速度快,内存利用率高,没有固定大小,扩展灵活;
缺点:不能随机查找,每次都是从第一个开始遍历(查询效率低);
3、哈希表结构:结合数组结构和链表结构的优点,从而实现了查询和修改效率高,插入和删除效率也高的一种数据结构;
常见的HashMap就是这样的一种数据结构
二、实现Node<K,V>
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;
}
}
三、get()和put()
1、get()方法:
(1)调用getNode方法,传入相应key的hash值和key;
(2)在数组非空,数组长度大于0,索引处数据不为空的情况来进入到步骤(3),否则返回null;
(3)判断数组在索引处的首个元素是否要查找的元素,如果是,则返回该节点,否则进入(4);
(4)如果是红黑树的节点类型,进入(5),如果是链表结点则进入(6);
(5)调用红黑树的查找方法进行查找结点,若找到则返回结点,否则,返回null;
(6)遍历链表,利用equals方法进行比较,若找到则返回结点,否则,返回null;
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}
2、put()方法
(1)调用putVal()方法,参数为key的hash值,key,value;
(2)判断存储元素的table是否为空,是则进行必要字段的初始化;
(3)根据hash值获得索引(数组下标),如果数组在此下标为空,则新建一个结点;否则进入(4);
(4)利用hash值和equals()计算数组首节点是否和key相同,如果key值相同,说明已经存在,则直接替换旧值,不同则进入(5);
(5)如果首节点下是已红黑树结构存储,则调用红黑树相应的节点添加方法进行添加节点;
(6)如果首节点下是链表结构,则遍历链表;
(7)如果该key在链表已经存在,则直接进行覆盖,否则添加到后续节点,此时如果添加后节点长度超过了树化长度(默认为8),则将链表转化为红黑树;
(8)最后检测HashMap的Size,如果大于临界值,则需要进行扩容操作(后续说明)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
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;
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 {
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;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
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();
afterNodeInsertion(evict);
return null;
}
三、HashMap的扩容操作
1、相应的初始化数据
//默认初始化数组容量为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//默认装载因子为0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//只有满足一下两个条件,链表才会转化为红黑树;
//树化的门槛为8,即某个数组下标下的链表长度不小于8
static final int TREEIFY_THRESHOLD = 8;
//HashMap的容量必须大于64,
static final int MIN_TREEIFY_CAPACITY = 64;
2、扩容机制: 当向容器添加元素的时候,会判断当前容器的元素个数,如果大于等于阈值–即当前数组的长度乘以加载因子的值(默认16*0.75=12)的时候,就要自动扩容。
扩容时机:
- 首次put时,先会触发扩容(算是初始化),然后存入数据,然后判断是否需要扩容;
- 不是首次put,则不再初始化,直接存入数据,然后判断是否需要扩容;
- capacity 即容量,默认16。
- loadFactor 加载因子,默认是0.75
- threshold 阈值。阈值=容量*加载因子。默认12。当元素数量超过阈值时便会触发扩容。
(1)如果容量不为0,且容量增大一倍后满足小于最大容量且目前容量小于最小容量,则将阈值增大一倍,转(4);
(2)如果阈值为0,则说明第一次进行初始化,将阈值赋予扩容后的容量,转(4);
(3)如果容量和阈值均为0,则直接赋予默认参数,转(4);
(4)如果阈值还为0,则设置阈值;
(5)如果HashMap不为空,则Map里的内容在扩容后需进行调整;
调整阶段:
(6)如果数组下的节点只有一个结点,重新计算相应的hash值,移到新表的相应位置;
(7)如果数组下的节点是红黑树,则进行红黑树的节点调整;
(8)如果数组下的节点时链表,进行链表的调整;
调整结束;
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
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"})
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;
}
}
}
}
}
return newTab;
}