1.HashMap的实现,讲的主要是jdk1.8的。HashMap中主要的知识点有:
1.使用的hash算法,也即hash(key)的计算逻辑
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
//之所以这样计算hash值的原因是,扩散key.hashCode()的高位到低位。由于
//table使用的是2的指数倍掩盖,许多在当前掩码上的hash总是产生冲突。
//(许多Float类型的key总是在小表上连续不断的冲突)。所以我们将高位上的影响下移。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2. put()方法的实现
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;
//如果table为null 或者长度为0,调用resize()方法,进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//判断tab数组中的(n - 1) & hash的位置是否为null
if ((p = tab[i = (n - 1) & hash]) == null)
//如果为null,说明之前没有存放过数据,将新节点放入tab数组中
tab[i] = newNode(hash, key, value, null);
else {
//说明tab[i]已经有数据了。可以考虑三种情况,
Node<K,V> e; K k;
//第一种是p.key==key,可以直接更新
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//第二种是p结点已经转换成红黑树的结构,可以把这个值存入的红黑树中。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//第三种 是链表结构
for (int binCount = 0; ; ++binCount) {
//判断下p.next是否为null,
if ((e = p.next) == null) {
//因为p.next == null,说明已经到了链表的尾部,可以直接插入结点
p.next = newNode(hash, key, value, null);
//如果链表的长度大于等于8,调整成红黑树的结构
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果说e.hash == hash,同时e.key == k,说明是同一个结点,不用存储了,直接返回。
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;
//onlyIfAbsent为true,则不改变e结点的值,但是在调用put方法的时候,
//onlyIfAbsent为false,说明是要更新的value值的,
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//返回原来旧的value值
return oldValue;
}
}
//保留修改的次数,用于HashMap中迭代器的快速失败。
++modCount;
//直接存放到数组中的个数大于阈值,就进行resize(),也就是扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
3. resize()方法的实现,就是扩容的实现
这里也存在一个疑问:oldTab[j] = null;是不是不应该清空的这么早啊。
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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;
}
//oldCap的两倍为newCap ,如果newCap<MAXIMUM_CAPACITY,oldCap也大于默认的初始容量,就进行扩容
//也说明newCap 为2 的指数倍增长
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//newThr 也是oldThr的2倍,也是指数倍增长
newThr = oldThr << 1; // double threshold
}
//
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//说明了oldCap 和oldThr都为0的情况,newCap为默认初始容量,newThr为默认初始容量*负载因子的取整
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);
}
//---------------以上都为计算newCap和newThr 逻辑。
//更新threshold属性的值为newThr
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//创建了一个的Node数组
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;
//e是只有一个节点的链表,直接e.hash &(newCap-1),进行定位,e.hash & (newCap-1)其实也是等于e.hash&(oldCap-1)
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;
//遍历e节点的链表,把这个链表分成hi,lo两个链表,目的是可以缩短链表的长度,并能够是数据更加散列
do {
next = e.next;
//低位,lo到了newTab中还是原来的相对位置上,hi是j+oldCap的位置上
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);
//lo链表存放到j的位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//hi链表存放到j+oldCap的位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
4. get()方法的实现
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
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) {
//直接定位到数组中对应的位置且key == key,直接返回第一个结点
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//说明first.key != key,需要在first.next节点中继续找
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;
}