HashMap源码解读(java8)
HashMap源码解读(java8)
HashMap的默认设置
静态变量
/**
* 初始容量,必须是2的n次幂,默认的初始容量是16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认的加载因子,0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 默认大小为8,当哈希桶数组中链表的长度大于8时,将转为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 默认大小为6,红黑树节点数量小于该值时将转为链表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 默认大小为64,hash表容量大于该值才可能转化为红黑树
*/
static final int MIN_TREEIFY_CAPACITY = 64;
静态内部类Node
接下来是内部声明了hashmap数据存储单元的结构:
/**
* Node是HashMap的一个内部类,实现了Map.Entry<K,V>接口,其实就是用来存储键值对。
* 其内部重写了equals和hasCode方法
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
java.util.HashMap.Node<K,V> next;
Node(int hash, K key, V value, java.util.HashMap.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;
}
}
实用方法
hash
hash计算,定位元素在同数组中的索引位置。具体的计算流程如下:
- h = key.hashCode() 取hashcode值
- h^(h >>> 16) 高位参与运算
- 还有隐藏的一步,在一些主要方法中会见到(n - 1) & hash,其实就是通过取模运算确定在数组中的索引位置
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
comparableClassFor
如果 x 的类的形式为“类 C 实现 Comparable
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
compareComparables
如果 x 匹配 kc(k 的筛选可比类),则返回 k.compareTo(x),否则返回 0
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x));
}
tableSizeFor
判断指定的初始化容量是否是2的n次幂,如果不是便返回比指定初始化容量大的最小的2的n次幂。比如int cap=10那么最终返回的结果为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;
}
成员变量
成员变量列表
/**
* 哈希桶数组,HashMap内部结构是由数组(Node[] table)、链表以及红黑树组成的
*/
transient Node<K,V>[] table;
/**
* 保存缓存的 entrySet()。请注意,AbstractMap 字段用于 keySet() 和 values()
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* hashmap中实际存储的键值对的数量
*/
transient int size;
/**
* 该 HashMap 被结构修改的次数。该字段用于在 HashMap 的 Collection-views 上创建迭代器快速失败。
*/
transient int modCount;
/**
* 扩容阈值,存储的键值对个数超过该值时,便要进行扩容操作。
*/
int threshold;
/**
* 加载因子,用于计算扩容阈值。扩容阈值=默认容量*加载因子。
*/
final float loadFactor;
引申-哈希桶数组
哈希桶数据的结构图如上,每个数组的位置就是一个hash值,这里采用了拉链法来减少冲突,即两个元素key的哈希值相同,便会占用同一个位置,形成链表。需要注意的是,当链表的长度超过TREEIFY_THRESHOLD时,链表会变更为红黑树结构存储。当红黑树中的元素个数不断减少到UNTREEIFY_THRESHOLD时,便会转为链表存储。
构造函数
HashMap(int initialCapacity, float loadFactor)
使用该方法可自定义初始容量和加载因子。
public HashMap(int initialCapacity, float loadFactor) {
//initialCapacity的范围应该在[0-Integer.MAX_VALUE],小于下界时报错,大于上界时使用默认的最大容量设置。
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);
}
需要注意的是,此时threshold变量的值跟初始容量相等,后面对Node<K,V>[] table进行初始化时会计算真正的threshold。或者说threshold暂存了容量大小capacity。
HashMap(int initialCapacity)
使用该方法可自定义初始容量,实际上还是是通过调用HashMap(int initialCapacity, float loadFactor) 这个构造方法。
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
HashMap()
使用默认设置,即初始化容量为16,加载因子为0.75。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
HashMap(Map<? extends K, ? extends V> m)
构造一个映射关系与指定 Map 相同的新 HashMap
public HashMap(Map<? extends K, ? extends V> m) {
//使用默认的加载因子
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
putMapEntries方法参见 成员方法-putMapEntries(Map<? extends K, ? extends V> m, boolean evict)
成员方法
putMapEntries(Map<? extends K, ? extends V> m, boolean evict)
源码解释
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//获取map的长度
int s = m.size();
//map中包含数据时才进行如下计算
if (s > 0) {
//如果table还没有初始化
if (table == null) { // pre-size
//计算出来一个容量,使得size刚好不大于阈值。加1是为了向上取整获得一个整数容量。
float ft = ((float)s / loadFactor) + 1.0F;
//判断计算出的容量是否合法
int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY);
//如果计算出的新容量大于threshold中行暂存的容量大小,则将新容量暂存在threshold中
if (t > threshold)
threshold = tableSizeFor(t);
}
//如果table已经初始化,并且map中的数据量大于扩容阈值threshold,则进行扩容操作
//这种情况时预先扩大容量,再put元素
else if (s > threshold)
resize();
//遍历map,将其中的所有元素添加到hashmap中
//注意:循环里的putVal可能也会触发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);
}
}
}
注
- float ft = ((float)s / loadFactor) + 1.0F;
size / loadFactor = capacity,但如果算出来的capacity是小数,却又向下取整,会造成容量不够大,所以,如果是小数的capacity,那么必须向上取整。
- if (t > threshold)
这里的threshold实际存放的值是capacity的值,因为在table还没有初始化时(table还是null),用户给定的capacity会暂存到threshold成员上去(毕竟HashMap没有一个成员叫做capacity,capacity是作为table数组的大小而隐式存在的)。
- else if (s > threshold)
说明传入map的size都已经大于当前map的threshold了,即当前map肯定是装不下两个map的并集的,所以这里必须要在循环放入新元素之前执行resize操作。而当s<=threshold时,还不能够确定是否需要扩容,所以会在putVal方法中有判断扩容的操作。
size()
功能
返回hashmap中的键值对数量
源码解释
public int size() {
return size;
}
isEmpty()
功能
判断hashmap是否为空
源码解释
public boolean isEmpty() {
return size == 0;
}
get(Object key)
功能
通过key查找value
源码解释
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
其中getNode方法参见getNode(int hash, Object key)
具体执行步骤
- 通过hash值获取该key映射到的桶,用到的方法是
hash()
- 桶上的key就是要查找的key,则直接找到并返回
- 桶上的key不是要找的key,则查看后续的节点:
a. 如果后续节点是红黑树节点,通过调用红黑树的方法根据key获取value
b. 如果后续节点是链表节点,则通过循环遍历链表根据key获取value
getNode(int hash, Object key)
功能
获取指定key的信息
参数说明
- hash: 目标key的hash值
- key: 要查找的key
源码解释
final Node<K,V> getNode(int hash, Object key) {
//临时变量存储table
Node<K,V>[] tab;
//first为获取的第一个元素,e为first的下一个元素
Node<K,V> first, e;
//table长度
int n;
//存储first.key
K k;
//如果table已经被初始化切table数组的长度大于0,在已知元素的查找位置上有元素则进入if判断。否则不存在该元素,返回null
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
//first元素存在且first元素就是要查找的元素,则直接返回first
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//若first元素不是要查找的元素,则继续检查first的下一个元素是否符合
if ((e = first.next) != null) {
//如果first是树节点,则进入红黑树查找
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//如果first是链表结点,则不断循环检查e是否是要查找的元素,若是,则直接返回e,若不是,则继续查看e的下一个元素
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
containsKey(Object key)
功能
判断是否存在指定key
源码解释
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
put(K key, V value)
功能
将键值对存入hashmap。若已存在key则用新值覆盖,否则插入
源码解释
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
其中putVal方法参见putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
put方法的执行步骤
-
通过hash值获取该key映射到的桶,用到的方法是
hash()
-
如果桶上没有碰撞冲突,则直接插入
-
如果出现碰撞冲突,则需要处理冲突
a. 如果该桶使用红黑树处理冲突,则调用红黑树的方法插入数据
b. 否则采用传统的链式方法插入。如果链的长度达到临界值,则把链转变为红黑树
putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
功能
将键值对插入hashmap
参数说明
- hash: key的hash值
- key: 要存放的key
- value: 要存放的value
- onlyIfAbsent: 如果true代表不更改现有的值
- evict: false表示table为创建状态
源码解释
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
//临时变量存储table
Node<K,V>[] tab;
Node<K,V> p;
//n为数组table的长度
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//若table未初始化,n的值为数组初始化好的长度
n = (tab = resize()).length;
//(n - 1) & hash 取模运算得到key在哈希桶数组的索引位置
if ((p = tab[i = (n - 1) & hash]) == null)
//p为当前key计算hash值之后的在哈希桶数组中的第一个节点,若为空,则表示没有哈希冲突,那么直接把键值对存入一个新节点并将该节点放入桶中
tab[i] = newNode(hash, key, value, null);
else {
//存在hash冲突则进行如下操作
Node<K,V> e;
K k;
//p为当前key计算hash值之后的在哈希桶数组中的第一个节点,若桶中的第一个元素的key与要存入的key相同,则将旧的第一个节点数据赋值给e
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//若hash值不同或key不同,则先判断是否是红黑树结构,若是,则按照红黑树方式插入数据
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//若hash值不同或key不同,且不是红黑树结构(即当前是链表)
//循环遍历链表的每一个节点,同时检查遍历到的每个key与要插入的key是否相同,若都不相同,新key将插入到链表末尾
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;
}
//若当前节点不是最后一个,判断当前位置的key与要插入的key是否相同。
//若相同则跳出循环
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
//p移到下一个节点
p = e;
}
}
//若e!=null,则说明原hashmap中存在要插入的key。且此时的e就是旧的<key, value>
if (e != null) { // existing mapping for key
//取出旧value
V oldValue = e.value;
//若旧value为null或者onlyIfAbsent为false时才使用新的value覆盖旧value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//访问后回调
afterNodeAccess(e);
//返回旧value
return oldValue;
}
}
//记录修改次数。fast-fail机制会用到
++modCount;
//插入数据完毕后,判断当前数据量是否达到扩容的阈值,超过则进行扩容操作
if (++size > threshold)
resize();
//插入后回调
afterNodeInsertion(evict);
return null;
}
注
- treeifyBin(tab, hash)参见
treeifyBin(Node<K,V>[] tab, int hash)
方法,resize()参见resize()
方法 afterNodeAccess
和afterNodeInsertion
方法,hashmap源码中方法体中没有具体实现,即是空方法,还有afterNodeRemoval
方法也是,这几个方法是为LinkedHashMap服务的。LinkedHashMap
是HashMap
的一个子类,它保留插入的顺序。这三个方法表示的就是在访问、插入、删除某个节点之后,进行一些处理,它们在LinkedHashMap都有各自的实现。LinkedHashMap正是通过重写这三个方法来保证链表的插入、删除的有序性。
resize()
功能
扩容,当元素个数超过 threshold 时,就会进行扩容。扩容是一个耗时操作。并且如果链表长度达到TREEIFY_THRESHOLD,但是数组长度未超过MIN_TREEIFY_CAPACITY时,会先进性扩容。
从代码中不难发现,hashmap扩容的时机有两种:
- 新建hashmap时不会对table初始化,在第一次插入数据时,进行resize来构建table
- 当hashmap的size超过threshold时,进行resize。后续的
threshold=table.length*loadFactor
,其中的table.length默认为16,loadFactor默认为0.75。
源码解释
final Node<K,V>[] resize() {
//oldTab存储当前数组
Node<K,V>[] oldTab = table;
//oldCap当前数组长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//oldThr当前扩容阈值
int oldThr = threshold;
//新数组的长度和扩容阈值
int newCap, newThr = 0;
//若旧数组长度大于0,计算扩容后的新数组的大小
if (oldCap > 0) {
//若旧数组长度达到最大值,那么便无法进行扩容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//若旧数组长度没有达到最大值,那么就尝试扩容,新数组大小为原来的两倍
//(newCap = oldCap << 1) < MAXIMUM_CAPACITY 扩容后的新数组大小应小于最大容量
//oldCap >= DEFAULT_INITIAL_CAPACITY 旧数组容量应大于数组默认的初始化长度
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//若就数组为空,说明旧数组还未初始化,即第一次向里面put数据时出发了resize,此时若使用构造函数指定了initialCapacity,则table的大小为threshold,因为扩容阈值暂存的是的数组容量
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//若table未初始化且构造方法中也没指定容量,那么新数组容量和扩容阈值均使用默认值
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//若在创建hashmap时指定了initialCapacity,需要计算新的threshold
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) {
//清除旧表对node结点的引用,此时e指向该node节点
oldTab[j] = null;
//若桶的当前位置只有一个节点,那么把这个节点e直接放入新桶中即可
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;
}
treeifyBin(Node<K,V>[] tab, int hash)
功能
将哈希桶对应位置的链表结构转为红黑树
参数说明
- Node<K,V>[] tab:桶数组
- int hash: 哈希值
源码解释
final void treeifyBin(Node<K,V>[] tab, int hash) {
//n为数组长度
int n, index; Node<K,V> e;
//如果当前数组为空或者数组的长度小于进行树形化的阈值(MIN_TREEIFY_CAPACITY = 64)就进行扩容,而不进行数化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//若数组的长度大于进行树形化的阈值(MIN_TREEIFY_CAPACITY = 64)
//根据hash值和数组长度进行取模运算后,得到链表的首节点e
else if ((e = tab[index = (n - 1) & hash]) != null) {
//hd为红黑树头节点,t1为红黑树尾节点
TreeNode<K,V> hd = null, tl = null;
do {
//使用当前链表节点e创建一个树节点p
TreeNode<K,V> p = replacementTreeNode(e, null);
//如果尾节点为空,说明还没有根节点
if (tl == null)
//将新建的p节点赋给红黑树头节点
hd = p;
else {// 尾节点不为空,建立一个双向链表结构
//前树节点的前一个节点指向尾节点
p.prev = tl;
//将现在节点p作为树的尾结点的下一个节点
tl.next = p;
}
//把当前节点设为尾节点
tl = p;
} while ((e = e.next) != null);//遍历链表每一个节点
//把转换后的双向链表,替换原来位置上的单向链表
if ((tab[index] = hd) != null)
//TreeNode类的treeify方法
hd.treeify(tab);
}
}
注
- resize()方法参加
resize()
方法
putAll(Map<? extends K, ? extends V> m)
功能
将指定map添加到已有map中
源码解释
public void putAll(Map<? extends K, ? extends V> m) {
//因为是将xinmap添加到已有map中,所以第二个参数为true,无需初始化map中的table
putMapEntries(m, true);
}
remove(Object key)
功能
移除指定key的键值对,若删除成功则返回指定节点的value,否则返回null
源码解释
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}
removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable)
功能
删除指定节点
参数说明
- hash key的hash
- key 要删除的key
- value 要删除的value
- matchValue 是否需要value也匹配,即key和value要同时符合时才删除
- movable
源码解释
final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
//暂存table
Node<K,V>[] tab;
//p为key的hash后的在table中的索引处的第一个节点
Node<K,V> p;
//n为table的长度,index为key的hash后的在table中的索引值
int n, index;
//如果table已经初始化且在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;
//若索引处的第一个节点就是要删除的key,那么将node指向为第一个节点p,准备删除
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 {
//找到要删除的节点后,将node指向要删除的节点
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
node = e;
//已经找到要删除的节点,退出循环,此时p.next=e,即p.next=node
break;
}
//继续下一个节点
p = e;
} while ((e = e.next) != 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);
//p之前说过是索引处的第一个节点,若node==p,则直接将索引处的节点指向p的下一个节点即可
else if (node == p)
tab[index] = node.next;
//否则,则将查找到的元素的上一个节点的next指向要删除节点的next节点,实现删除
else
p.next = node.next;
//修改次数加1
++modCount;
//hashmap的size减1
--size;
//删除节点回调
afterNodeRemoval(node);
//返回删除掉的节点
return node;
}
}
//table未初始化或未找到目标节点,返回null
return null;
}
clear()
功能
清空hashmap,清空后table的大小不变,每个索引处都是null
源码解释
public void clear() {
Node<K,V>[] tab;
//操作次数加1
modCount++;
//若桶中有数据,则将每个索引处的数据置为null,同时桶的长度置0
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
containsValue(Object value)
功能
查找hashmap中有无指定的value
源码解释
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
//若table中有数据
if ((tab = table) != null && size > 0) {
//对table遍历
for (int i = 0; i < tab.length; ++i) {
//对每个桶中的节点遍历
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
//若找到相同value的节点则查找成功,返回true
if ((v = e.value) == value || (value != null && value.equals(v)))
return true;
}
}
}
//查找失败返回false
return false;
}
keySet()
功能
返回hashmap的key的集合
源码解释
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
values()
功能
返回 hashMap 中存在的所有 value 值的集合
源码解释
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
entrySet()
功能
返回 hashMap 中存在的所有键值对的集合
源码解释
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();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
getOrDefault(Object key, V defaultValue)
功能
获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值
源码
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
putIfAbsent(K key, V value)
功能
如果 hashMap 中不存在指定的键,则将指定的键/值对插入到 hashMap 中。
源码
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
remove(Object key, Object value)
功能
删除 hashMap 中指定键 key 的映射关系
源码
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
replace(K key, V oldValue, V newValue)
功能
如果key对应的value为oldValue,则将oldValue替换为newValue
源码
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> 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;
}
replace(K key, V value)
功能
替换 hashMap 中指定的 key 对应的 value。
源码
@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
功能
对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hasMap 中。如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值
源码
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (mappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
V oldValue;
if (old != null && (oldValue = old.value) != null) {
afterNodeAccess(old);
return oldValue;
}
}
V v = mappingFunction.apply(key);
if (v == null) {
return null;
} else if (old != null) {
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
return v;
}
computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
功能
对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值
源码
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
Node<K,V> e; V oldValue;
int hash = hash(key);
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
V v = remappingFunction.apply(key, oldValue);
if (v != null) {
e.value = v;
afterNodeAccess(e);
return v;
}
else
removeNode(hash, key, null, false, true);
}
return null;
}
compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
功能
对 hashMap 中指定 key 的值进行重新计算。如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值
源码
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
V oldValue = (old == null) ? null : old.value;
V v = remappingFunction.apply(key, oldValue);
if (old != null) {
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
}
else if (v != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return v;
}
merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
功能
添加键值对到 hashMap 中。如果 key 对应的 value 不存在,则返回该 value 值,如果存在,则返回通过 remappingFunction 重新计算后的值
源码
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (value == null)
throw new NullPointerException();
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
if (old != null) {
V v;
if (old.value != null)
v = remappingFunction.apply(old.value, value);
else
v = value;
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
return v;
}
if (value != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, value);
else {
tab[i] = newNode(hash, key, value, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return value;
}
forEach(BiConsumer<? super K, ? super V> action)
功能
对 hashMap 中的每个映射执行指定的操作
源码
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
功能
将 hashMap 中的所有映射关系替换成给定的函数所执行的结果
源码
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Node<K,V>[] 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<K,V> e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗