今天學習了 集合,但是感覺對于疊代器不是 很明白,是以研究了一下!
在 JDK中
Collection作為集合的頂級容器, 她實作了Java.lang.Iterable 接口!
Iterable: 可疊代的, 想使用疊代功能的容器必須實作這個頂級接口,中的 iterator() 方法。
Iterator:疊代器. 每個容器的内部都有不同的疊代器實作。抽取出她們的共性,我們抽取出
Iterator 接口。
我們檢視源碼
Iterator:
public interface Iterator {
boolean hasNext();
E next();
void remove();
}
Iterable:
public interface Iterable {
Iterator iterator();
}
下面我們分析一下 疊代器 是 如何實作的?
1 如果AbstractList 類,要使用疊代器。 她必須實作 Iterable.
2 在AbstractList 代碼中必須實作 Iterator iterator(){};
傳回 疊代器的接口或子類 引用。
2 在 AbstractList 代碼中,定義一個内部類,實作 Iterator 接口。
制定自己的 疊代器實作!
AbstractList 源碼實作:
目前索引
int cursor = 0;
上一次的索引位置
int lastRet = -1;
int expectedModCount = modCount;
判斷是否 有下一個元素
public boolean hasNext() {
return cursor != size();
}
擷取下一個元素
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
去掉元素
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
檢查異常
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}