zoukankan      html  css  js  c++  java
  • JDK8 HashMap--removeNode()移除节点方法

     1 /*删除节点*/
     2     final Node<K,V> removeNode(int hash, Object key, Object value,
     3                                boolean matchValue, boolean movable) {
     4         Node<K,V>[] tab; Node<K,V> p; int n, index;// 定义节点数组tab用于指向table、节点p、数组长度n、hash所映射的数组下标
     5         if ((tab = table) != null && (n = tab.length) > 0 &&
     6             (p = tab[index = (n - 1) & hash]) != null) {// 节点数组在hash位置处的节点不为空,若为空则直接返回null(不存在可删除元素)
     7             Node<K,V> node = null, e; K k; V v;// 定义局部节点变量node存储需要删除的元素、循环变量e、key、value
     8             if (p.hash == hash &&
     9                 ((k = p.key) == key || (key != null && key.equals(k))))// 头结点即为需要删除的节点
    10                 node = p;
    11             else if ((e = p.next) != null) {// 链表还存在其他元素,并将e指向头结点的后继元
    12                 if (p instanceof TreeNode)// 该链表是一个红黑树结构
    13                     node = ((TreeNode<K,V>)p).getTreeNode(hash, key);// 在红黑树中查询指定hash、key的节点并返回
    14                 else {// 链表是一个单项链表
    15                     do {
    16                         if (e.hash == hash &&
    17                             ((k = e.key) == key ||
    18                              (key != null && key.equals(k)))) {
    19                             node = e;// 节点e时需要移除的节点,结束循环
    20                             break;
    21                         }
    22                         p = e;// 循环结束时,节点p为目标节点的前驱元
    23                     } while ((e = e.next) != null);
    24                 }
    25             }
    26             if (node != null && (!matchValue || (v = node.value) == value ||
    27                                  (value != null && value.equals(v)))) {// 存在需要移除的节点且值匹配删除为false或者不为false且值匹配
    28                 if (node instanceof TreeNode)// node为树形节点,使用treeNode的移除方法
    29                     ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
    30                 else if (node == p)// 若node为头结点,直接将node 的后继元作为新的头结点
    31                     tab[index] = node.next;
    32                 else
    33                     p.next = node.next;// 链表下移除节点且不为头结点,此时将目标节点的前驱元的后继元指向目标节点的后继元
    34                 ++modCount;
    35                 --size;
    36                 afterNodeRemoval(node);
    37                 return node;
    38             }
    39         }
    40         return null;
    41     }
  • 相关阅读:
    负载均衡算法(四)IP Hash负载均衡算法
    负载均衡算法(二)加权轮询负载均衡算法
    负载均衡算法(一)轮询负载均衡算法
    移动端媒体查询CSS3适配规则
    JavaScript中label语句的使用
    NODE简易综合应用服务器搭建
    ES6--不定参数
    ES6--默认参数表达式,参数变动
    node基础学习——http基础知识-02-http响应数据流
    node基础学习——http基础知识-01-客户单请求
  • 原文地址:https://www.cnblogs.com/flydoging/p/10385644.html
Copyright © 2011-2022 走看看