共同学习Java源代码-数据结构-HashMap(十三)

来源:互联网 发布:多益网络客户端 编辑:程序博客网 时间:2024/05/20 11:19

现在来看各个迭代器 首先看迭代器的基类

    abstract class HashIterator {

        Node<K,V> next;        // next entry to return

这个属性代表下一个迭代的节点

        Node<K,V> current;     // current entry

这个属性代表当前节点

        int expectedModCount;  // for fast-fail

这个是期待的改变次数 用于判断是否出现并发异常

        int index;             // current slot
这个代表下标

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

这个是构造方法 首先将modCount赋值给期待的改变次数变量 确保两个变量是一致的 

然后将哈希桶数组赋给临时变量t 然后将current和next清空 将index设为0 

判断哈希桶数组不为空且存有键值对 进入空的do while循环 将next指向哈希桶数组第一个元素 



        public final boolean hasNext() {
            return next != null;
        }

判断有无下一个元素的方法 就是看next是否为空


        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

这个方法是获取下一个节点的方法 

先创建临时变量t和e e赋值为next 

判断两个修改次数是否一致 不一致就抛出并发异常 

判断如果e 也就是next为空 就抛出没有元素异常

将e赋给current 也就是将原本的next赋给current 将新的current的next赋给next 也就是将下下一个赋给下一个 判断如果新的next为空 且争个哈希桶数组不为空 就进入do while循环 将next元素指向哈希桶数组下一个元素 其实呢就是遍历一个链表到尾部了 换一个链表遍历


        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;

        }

这个是删除方法 

先将current赋给临时变量p

判断如果p为空 就抛出异常

判断如果两个修改次数不一致 就抛出并发异常

将current置空 然后删除current元素 将两个修改次数进行统一

    }



阅读全文
0 0
原创粉丝点击