本文转自:https://blog.youkuaiyun.com/qq_37611061/article/details/80143475
iteraotr与for循环foreach的比较:
https://blog.youkuaiyun.com/zxq1138634642/article/details/8092327?utm_source=blogxgwz0
概要:collection(set和list的父接口)中实现了Iteraor接口
问题一:那Iterator是为什么存在?其实呢,在java中的许多容器中,他们的都需要遍历这个操作,所以能就定义了这个Iterator这个接口还实现多态,减少代码的耦合。
问题二:通常集合实现遍历是使用如下的方法:以ArrayList为例
Iterator itr=ArrayList.lterator;//ArrayList中的iterator方法实际上返回的就是一个Iterator实现类的对象,这个实现类中在集合中定义,作为集合类的内部类
while(itr.hasnext()){
system.in.println(itr.next());
}
问题三:集合中有关于迭代器实现内部类是怎么样定义的呢,这个内部类中有三个方法:hasnext (),next(),remove();具体定义如下:
public boolean hasNext()
{
return cursor != size;//当cursor不等于size时,表示仍有索引元素
}
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;
return (E) elementData[lastRet = i];
}
final void checkForComodification()
{
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}