# HashMap源代码分析·上

## 成员变量

// 默认起始容量-必须是2^n
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;

/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;

/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;

transient Node<K,V>[] table;

## 链表节点

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;// 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; }
// 这个hash值计算的是整个键值对的hash值
public final int hashCode() {
// key的hash与value的hash相与
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;
}
}

public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

## 构造函数

// 指定加载因子与起始容量
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
throw new IllegalArgumentException("Illegal load factor: " +
this.threshold = tableSizeFor(initialCapacity);
}
// 指定起始容量，加载因子默认
public HashMap(int initialCapacity) {
}
// 全部默认
public HashMap() {
}

 // 对给定的容量，比它大的2^n值
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

1000 1000 >>> 1 = 0100
1000 | 0100 = 1100

1100 >>> 2 = 0011
1100 | 0011 = 1111

1111 >>> 4 = 0000
1111 | 0000 = 1111
0100 0100 >>> 1 = 0010
0100 | 0010 = 0110

0110 >>> 2 = 0001
0110 | 0001 = 0111

0111 >>> 4 = 0000
0111 | 0000 = 0111

capacity tableSizeFor()
1 1
3 4
9 16
24 32

public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>(12, 0.74f);
printHashMapCapacity(map);
}
public static void printHashMapCapacity(HashMap map){
if (map == null)
throw new IllegalArgumentException("what the fu*king arguments for : "+map);
Class<HashMap> clz = HashMap.class;
try {
Method method = clz.getDeclaredMethod("capacity");
method.setAccessible(true);
System.out.println("capacity : "+(int)method.invoke(map)+", size : "+map.size());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
---
capacity : 16, size : 0

final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}

## 增加键值对

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* 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.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

java中int是32位的。键为时就为0，否则先得到键的hashCode()，然后其无符号右移16位后，再与原数异或。这之后才得到键的hash值。为什么要这样算。。没太明白，所以还是把注释贴上去吧。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果桶数组为空，那么将利用resize()初始化一个桶数组
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 此处的位置，为什么还需要将hash与length-1？所以位置不是hash值？
// 好像不太对，n = 2^m，所以n-1应该是全1的某个数，如7,15。
// 因此位置还应该是hash值。
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;// 若键值对的hash,key都相同，则将p暂存到e中
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {// 键值不相同，从next遍历后续链表，如果存在就替换，不存在就添加到其上。
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;// 选择跳出，说明找到相同的键，并将该节点暂存到e中
p = e;// p指向e，即p.next，也就是p节点的下一个
}
}
if (e != null) { // e不为空说明键已存在
V oldValue = e.value;
// 之前传进来的值起作用了。传进来的是false，此时会替换。
// 如果是true的话，且旧值为空，还是会替换。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);// 一个回调
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();// 同样的，要变身
afterNodeInsertion(evict);// 还是一个回调
return 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;
}
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;
}
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)//该桶没有后续的节点
// 新数组上的位置可能与之前不同，可能是二倍
// newCap-1为0b11...11样式的二进制，比oldCap-1多一位1
// 相与的话，取决于hash值的前一位。所以可能是相同，可能是(原位置➕原容量)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 对拥有后续链表的桶，另做处理
// lo应该是low的缩写，hi是high的缩写，表示0或1
// 哪里的0或1呢？这是关键点，继续看
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 遍历该桶的所有节点
do {
next = e.next;
// e.hash & oldCap这个与之前的位置有什么差别呢？
// 之前算位置时，是用oldCap-1与hash相与，也就是1111...1样式的二进制，
// 现在是10000..00样式的二进制，所以等不等于0
// 取决于hash值的前1位。
if ((e.hash & oldCap) == 0) {
// 为什么要用这个loTail？也就是尾。后续需要将尾位置上的节点的next指向e，也就是else所执行的。
if (loTail == null)// 说明还没有数据
else
loTail.next = e;// 尾->next
loTail = e;// 尾 = e;
}
else {
// 逻辑同上，此时位置的二进制的第一位是1
if (hiTail == null)
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 组成了一个新的链表，位置在之前的位置的位置上，因为第1位为0
if (loTail != null) {
loTail.next = null;
}
// 组成一个新的链表，位置是原位置+原容量，因为第1位为1
if (hiTail != null) {
hiTail.next = null;
}
}
}
}
}
return newTab;
}

## 查询元素

public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

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;
}

## 删除键值对

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;
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;
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为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);
else if (node == p)// 在桶数组上
tab[index] = node.next;
else// 在链表上，将前个节点的后续改成该键值对的后续，即实现删除了该键值对
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

01-23 423

06-10 1589

07-19 35

06-24 5069

11-30 6702

01-19 28

01-29 97

05-08 5787

04-24 4万+

#### jdk1.8 HashMap工作原理和扩容机制(源码解析)

©️2020 CSDN 皮肤主题: 终极编程指南 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。