public interface Iterator<E> {
boolean hasNext();//有元素可以迭代,则返回 true。
E next();//返回迭代的下一个元素。
default void remove() {
//从底层集合中删除此迭代器返回的最后一个元素(可选操作)。
throw new UnsupportedOperationException("remove");
}
//对每个剩余元素执行给定的操作,直到所有元素都被处理或动作引发异常。
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
简单实现
public class IteratorImpl implements Iterator {
private final Object[] elementData;
private int nextIndex = 0;// 下一个索引
int expectedModCount = elementData.length;// 操作数
public IteratorImpl(Object[] elementData) {
this.elementData = elementData;
}
@Override
public boolean hasNext() {//:如果仍有元素可以迭代,则返回 true。
return nextIndex!=elementData.length;
}
@Override
public Object next() {//返回迭代的下一个元素。
checkForComodification();
if (nextIndex>=elementData.length)
throw new IndexOutOfBoundsException("索引越界");
nextIndex++;
return elementData[nextIndex-1];
}
public static void main(String[] args) {
String str0 = "abc";
String str1 = "123";
String str3 = "3rs";
String[] data = {str0,str1,str3};
IteratorImpl iterator = new IteratorImpl(data);
for (int i = 0; i < 5; i++) {
if (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
}
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;// 操作数
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
//使用迭代器的过程中,不要随意改变集合长度,否则,会出现ConcurrentModificationException(并发修改异常)
checkForComodification();
///源码///
//final void checkForComodification() {
// if (modCount != expectedModCount)throw new ConcurrentModificationException();
//}
/
//ConcurrentModificationException
int i = cursor;
if (i >= size)
//Exception in thread "main" java.util.NoSuchElementException->没有这样的元素
/*
*原因:我们存元素的个数,和调用next()方法的次数不符合,所以出现了问题
*解决:不要在while中连续多次next()
*/
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
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();
}
}