抽象类HashIterator,HashMap中的迭代器,都来自于HashIterator迭代器
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() { //构造方法,初始化HashIterator对象
expectedModCount = modCount; //将记录hashMap修改次数的modCount赋值给expectedModCount,
// 如果后续expectedModCount和modCount的值不一致了,说明有其他线程修改modCount的值,此时会抛出异常
Node<K,V>[] t = table; //把成员变量table赋值给Node类型的节点t;
current = next = null; //第一次执行到这里时,当前节点current等于next节点;
index = 0;//t数组的下标;
if (t != null && size > 0) { // advance to first entry //t不为null时找到t中不为空的元素后跳槽循环
do {} while (index < t.length && (next = t[index++]) == null);//t.length初始值=16,next=t[index++]为空时继续do循环,看不到过程,
//不为空时跳出循环,找到next元素;
}
}
public final boolean hasNext() { //判断是否有下一个元素
return next != null;
}
final Node<K,V> nextNode() { //寻找下一个节点
Node<K,V>[] t; //定义Node类型的节点t,用于存放元素;
Node<K,V> e = next;//把HashIterator的成员变量next赋值给Node类型的节点e,此时next一般有值,除非hashMap中只有一个节点;
if (modCount != expectedModCount)//如果expectedModCount和modCount的值不一致了,说明有其他线程修改modCount的值,此时会抛出异常
throw new ConcurrentModificationException();
if (e == null) //如果e为空,说明hashMap中没有元素,抛出异常
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {//把e节点赋值给current,next=e.next能遍历节点,把table赋值给t,t不为空时,
//通过do-while循环找到不为空的元素;
do {} while (index < t.length && (next = t[index++]) == null); // t.length初始化=16,next不为空时,继续找,直到next=t[i]为空时继续循环,不为空时退出do循环
}
return e; //返回找到的不为空的节点
}
public final void remove() {
Node<K,V> p = current; //定义Node类型的节点p,把当前节点current赋值为p, HashIterator()和nextNode()都有对current赋值;
if (p == null)//如果p为空,抛出异常
throw new IllegalStateException();
if (modCount != expectedModCount)//如果expectedModCount和modCount的值不一致了,说明有其他线程修改modCount的值,此时会抛出异常
throw new ConcurrentModificationException();
current = null;//把当前节点current置为null;
removeNode(p.hash, p.key, null, false, false);//调用hahsMap的removeNode方法,删除节点;
expectedModCount = modCount;//同步下expectedModCount的计数;
}
}