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

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

    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元素 将两个修改次数进行统一

    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值