现在来看各个迭代器 首先看迭代器的基类
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是否为空
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元素指向哈希桶数组下一个元素 其实呢就是遍历一个链表到尾部了 换一个链表遍历
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元素 将两个修改次数进行统一
}