迭代器
ArrayList有返回迭代器的方法
1
2
3public Iterator<E> iterator() {
return new Itr();
}Itr实现Iterator
接口 1
2
3
4
5
6
7
8
9
10
11
12
13private 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(); //判断是否还有值
public E next() ; //返回下一个
public void remove() ; //删除
public void forEachRemaining();
final void checkForComodification();
hasNext()
- 只要cursor不等于size还存在元素
1
2
3public boolean hasNext() {
return cursor != size;
}
next()
- cursor一开始默认是0的,在数组的首元素开始
1
2
3
4
5
6
7
8
9
10
11public 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];
}
remove()
1 | public void remove() { |
forEachRemaining()
1 |
|
checkForComodification()
- modCount只要不被修改,代表原来容器没被修改,那么使用已经创建的迭代器进行操作也是允许的
1
2
3
4final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}