如何进行Iterator中的Itr类的分析
1.Itr类的概述
Itr类是Iterator接口的内部类,它实现了Iterator接口,并且提供了一种迭代访问集合中元素的方法。它的构造函数需要一个Collection类型的参数,而且只能在Iterator接口中调用,不能在外部类中调用。
2.Itr类的实现
Itr类实现了Iterator接口,它提供了hasNext()和next()方法,用于访问集合中的元素。hasNext()方法用于检测集合中是否还有元素,next()方法用于获取下一个元素。此外,Itr类还实现了remove()方法,用于删除集合中的元素。
3.Itr类的代码实现
public 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;
final ArrayList<E> list;
Itr(ArrayList<E> list) {
this.list = list;
}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = list.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 {
list.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = list.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
猜您想看
-
Linux下如何使用Samba进行文件共享
Linux下使...
2023年05月10日 -
为什么电脑无法正常进入BIOS设置界面?
如何解决电脑无...
2023年04月24日 -
进程管理与监控
进程概述进程是...
2024年05月30日 -
如何在宝塔中设置 Nginx 负载均衡超时时间
宝塔Nginx...
2023年05月08日 -
如何保护苹果手机上的隐私?
如何保护苹果手...
2023年04月27日 -
Python中怎么利用pubmed实现自动抢票功能
一、什么是Pu...
2023年05月26日