1.迭代器几个方法的实现原理:主要使用游标来记录;
1.1数组列表的方式:可以使用一个游标来指向数组的头部,hashnext就是查看判断游标的大小是否大于数组的大小,如果小于hashnext'就会移动游标;在linklist中的实现就更加简单了;
1.2hashSet中的迭代器中使用双重for循环分别遍历数组,以及链表;
下面是迭代器在ArrayList中的实现:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;//通过size来确定集合是否遍历完成
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)//抛出没有这个元素异常
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;//获得存储元素的数组
if (i >= elementData.length)//抛出并发修改异常
throw new ConcurrentModificationException();
cursor = i + 1;//游标增加1
return (E) elementData[lastRet = i];//当前游标返回出去就是next
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}