Entry
HashIterator() {
expectedModCount = modCount;
Entry[] t = table;//当前HashMap的table
int i = t.length; //注意,这里i是table的长度,而不是HashMap中的元素个数
Entry
if (size != 0) {
while (i > 0 && (n = t[--i]) == null)//i>0且t[i]==null;从table尾部开始,找到第一个不为Null的位置
;
}
next = n;//next此时指向从table尾部开始向前第一个不为Null的位置,index为该位置索引
index = i;
}
//如果next为null,说明table的第一个位置为Null(即table[0]==null),显然此时为空
public boolean hasNext() {
return next != null;
}
//从下面这个函数中可以看出nextEntry()是从table尾部向前遍历的,如遇hash冲突链,则会冲链头开始遍历
Entry
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry
if (e == null)
Entry
Entry[] t = table;
int i = index;
//如果n为null,即该处不存在hash冲突链表,则table继续向前
//那么如果n不为Null,则它此时是指向冲突链表的下一个位置
while (n == null && i > 0)
n = t[--i];
index = i;//如果n不为Null,则索引位置将不发生变化
next = n;
return current = e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
至此,HashSet的实现已经了然了。。
摘自 JieTouLangRen的专栏