本文都是作者自己的学习笔记,没有权威的参考价值,有错漏或者不足的地方请见谅。
// 默认的初始容量,2^4,初始大小为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 设定的最大容量,就是超过这个容量后,不再进行将原长度乘以二的扩展,而是直接设为Integer的最大值。
// 这个容量为2^30 = 1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的扩展因子,当数组中的元素个数大于 数组长度*扩展因子 时,进行长度扩展
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 进行构建二叉树的标志,当hash冲突所产生的冲突链表大于8个元素时,将链表重构为二叉树
static final int TREEIFY_THRESHOLD = 8;
// 当冲突元素被remove后的数量小于该常量时,就将二叉树解开
static final int UNTREEIFY_THRESHOLD = 6;
// 当数组容量小于这个值时,冲突元素大于二叉树界限时,选择进行数组扩展来规避冲突,大于这个值时,就直接进行二叉树构建。
static final int MIN_TREEIFY_CAPACITY = 64;
// HashMap的底层结构,就是一个Node的数组
transient Node[] table;
// 将map包装成一个set
transient Set> entrySet;
// 元素个数
transient int size;
// 记录操作的次数,防止两个进程同时修改,例如当使用iterator()时,Iterator会记录modCount,如果其记录的与实际的不同,就抛出异常
transient int modCount;
// 扩展界限,当元素个数超过这个值的时候,就进行一次resize
int threshold;
// 扩展因子,上面的threshold就是通过 数组长度 * loadFactor 计算出来的
final float loadFactor;
// 自定义容量和扩展因子的构造方法
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
// 以上构造方法使用的函数,会将容量设置为第一个大于或等于输入容量的2的n幂次,比如输入10,那就会设置成2^4,就是16
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;
}
// 自定义容量的构造方法,将扩展因子设定为默认0.75
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 默认空构造器
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
// 通过已有的Map集合构建
public HashMap(Map extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
// 将已有集合放入本对象的数组中
final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
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);
}
}
}
// HashMap产生key的hash值的函数
static final int hash(Object key) {
int h;
// 将高16位与低16位异或
// 这样做,如果两个key的低16位的hash相同但是高16位不相同,就不会因为低16位相同而产生冲突,可以规避相当一部分冲突
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 用户调用的存放函数
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// 只有在键不存在或者键所对应的值为null时,才存入,即不会替换已有的键值对
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 这个语句是很重要的语句,就是用来确定该将元素放入数组的哪个数组,下面会放图来解释怎么通过Hash值放入数组对应位置中
// 没有hash冲突,即所对应的位置为空时,直接放入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 处理hash冲突
Node e; K k;
// 如果key的hash一样并且equals,那就认为是同一个key,将其内容替换
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)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;
}
// 放入一个集合中的所有元素
public void putAll(Map extends K, ? extends V> m) {
putMapEntries(m, true);
}
// 具体方法,可以看到是先判断进行扩展,随后调用putVal()函数去遍历放入。
final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
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);
}
}
}
如何通过hash值和数组长度确定元素在数组中的长度
4、获得元素的相关方法
// 通过键去获取值
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
// 底层获取方法
final Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
// 通过长度异或键的hash得出数组位置
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 确认是该键而不是hash冲突
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)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;
}
// 当没有查找到key对应的值时,会返回传入的默认值
@Override
public V getOrDefault(Object key, V defaultValue) {
Node e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
5、替换方法
// 用新的值替换旧的值,如果键不存在,就返回false
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
// 用传入的值替换旧值并返回,如果本身为空,不替换,直接返回
@Override
public V replace(K key, V value) {
Node e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
// 这是对值进行群体操作的函数,形式是replaceAll(value -> value * value)
@Override
public void replaceAll(BiFunction super K, ? super V, ? extends V> function) {
Node[] tab;
if (function == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
6、基本方法
// 扩容方法,每次扩展两倍,如果扩展时大于MAXIMUM_CAPACITY,就是设定为MAXIMUM_CAPACITY,但是如果原来就等于这个值时,扩展为int型的最大值
final Node[] resize() {
Node[] 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[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node 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)e).split(this, newTab, j, oldCap);
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node 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;
}
// 构建二叉树的方法,会检测数组长度,冲突个数是否超过最低限制
final void treeifyBin(Node[] tab, int hash) {
int n, index; Node e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode hd = null, tl = null;
do {
TreeNode 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);
}
}
3、在处理hash冲突时会使用链表或者二叉树。