一盒刚,迭代器
在對(duì)向量腺劣、列表和序列進(jìn)行處理(比如,查找某一特定的元素)時(shí)伪冰,一種典型的操作就是依次訪問或修改其中的各個(gè)元素誓酒。迭代器是軟件設(shè)計(jì)的一種模式,它是對(duì)** “逐一訪問所有元素” **這類操作的抽象贮聂。
迭代器本身也是一個(gè)序列S靠柑,在任何時(shí)候,迭代器中都有唯一的當(dāng)前元素吓懈。迭代器還必須提供某種機(jī)制歼冰,使得我們可以不斷轉(zhuǎn)向S中的下一元素,并將其置為新的當(dāng)前元素耻警。與前面所介紹的** 位置ADT 相比隔嫡,迭代器是對(duì)前者的擴(kuò)展與推廣。 實(shí)際上甘穿,一個(gè)位置本身已經(jīng)可以被看作是一個(gè)迭代器了腮恩,只不過它還不能不斷更新。 ** 總之温兼,所謂迭代器秸滴,就是對(duì)一組對(duì)象之間的位置、直接后繼等關(guān)系的集成募判。
二荡含,迭代器ADT(AbstractDataType)
操作方法 | 功能描述 |
---|---|
hasNext() | 檢查迭代器中是否還有剩余的元素 輸入:無 輸出:布爾標(biāo)志 |
getNext() | 返回迭代器中的下一元素 輸入:無 輸出:對(duì)象 |
三,基于列表實(shí)現(xiàn)的迭代器
接口:
package dsa.Iterator;
/*
* 迭代器ADT接口
*/
public interface Iterator {
boolean hasNext();// 檢查迭代器中是否還有剩余的元素
Object getNext();// 返回迭代器中的下一元素
}
異常:
package dsa.Iterator;
public class ExceptionNoSuchElement extends RuntimeException {
public ExceptionNoSuchElement(String err) {
super(err);
}
}
- 基于列表實(shí)現(xiàn)的位置迭代器:
package dsa.Iterator;
import dsa.List.List;
import other.Position;
/*
* 基于列表實(shí)現(xiàn)的位置迭代器
*/
public class IteratorPosition implements Iterator {
private List list;// 列表
private Position nextPosition;// 當(dāng)前(下一個(gè))位置
// 默認(rèn)構(gòu)造方法
public IteratorPosition() {
list = null;
}
// 構(gòu)造方法
public IteratorPosition(List L) {
list = L;
if (list.isEmpty())// 若列表為空届垫,則
nextPosition = null;// 當(dāng)前位置置空
else
// 否則
nextPosition = list.first();// 從第一個(gè)位置開始
}
// 檢查迭代器中是否還有剩余的位置
public boolean hasNext() {
return (nextPosition != null);
}
// 返回迭代器中的下一位置
public Object getNext() throws ExceptionNoSuchElement {
if (!hasNext())
throw new ExceptionNoSuchElement("意外:沒有下一位置");
Position currentPosition = nextPosition;
if (currentPosition == list.last())// 若已到達(dá)尾位置释液,則
nextPosition = null;// 不再有下一個(gè)位置
else
// 否則
nextPosition = list.getNext(currentPosition);// 轉(zhuǎn)向下一位置
return currentPosition;
}
}
- 基于列表實(shí)現(xiàn)的元素迭代器:
package dsa.Iterator;
import other.Position;
import dsa.List.List;
/*
* 基于列表實(shí)現(xiàn)的元素迭代器
*/
public class IteratorElement implements Iterator {
private List list;// 列表
private Position nextPosition;// 當(dāng)前(下一個(gè))元素的位置
// 默認(rèn)構(gòu)造方法
public IteratorElement() {
list = null;
}
// 構(gòu)造方法
public IteratorElement(List L) {
list = L;
if (list.isEmpty())// 若列表為空,則
nextPosition = null;// 當(dāng)前元素置空
else
// 否則
nextPosition = list.first();// 從第一個(gè)元素開始
}
// 檢查迭代器中是否還有剩余的元素
public boolean hasNext() {
return (null != nextPosition);
}
// 返回迭代器中的下一元素
public Object getNext() throws ExceptionNoSuchElement {
if (!hasNext())
throw new ExceptionNoSuchElement("意外:沒有下一元素");
Position currentPosition = nextPosition;
if (currentPosition == list.last())// 若已到達(dá)尾元素装处,則
nextPosition = null;// 不再有下一元素
else
// 否則
nextPosition = list.getNext(currentPosition);// 轉(zhuǎn)向下一元素
return currentPosition.getElem();
}
}