HashMap源码分析3:移除
2024-09-30 22:41:05
本文源码基于JDK1.8.0_45。
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;
//如果HashMap未初始化或哈希值对应下标无节点,不需要执行移除操作
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);
}
}
//如果移除前需要判断节点的值,则目标值与原值相等才能移除
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;
//如果是链表结构,则前序节点的next指向要移除节点的下一个节点
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
最新文章
- 总结项目开发中用到的一些css\html技巧
- HttpWebRequest调用WebAPI
- CentOS7服务器相关配置
- HTTP请求中的User-Agent 判断浏览器类型的各种方法 网络爬虫的请求标示
- 西秦的ACE-Python教程 一、Python本地开发环境部署
- 关于 C/C++ 的文章
- hbase使用-java操作
- oc-05-对象的创建
- adobe 蛋疼的套装, 想安装一个Flash Professional CS6,标准版还没有...
- git configuration
- Mysql数据库中的EXISTS和NOT EXISTS
- XML文件编码问题
- FineReport单元格扩展与父子格设置
- [python学习笔记] py2exe 打包
- PHP读取数据库表显示到前台
- BZOJ4711 小奇挖矿
- Scala中foldLeft的总结
- 引入CSS的三种方式
- vi/vim键盘对应图
- VS2010发布、打包安装程序(超全超详细)