接口實現:
Iterator接口包含三個方法:hasNext、next、remove。
迭代器的位置不是在某一個元素上,而是在集合中第一個元素之前、兩個元素之間或最後一個元素之後。
public interface Iterator<T> {
/**
* Task:測定迭代器是否完成遍歷並越過數據集的最後一個元素
* @return 迭代器若有下一個元素返回 true
*/
public boolean hasNext();
/**
* Task:提取集合中當前(下一個)元素 並迭代前進下一個位置
* @return 迭代當前元素的引用
* @throws java.util.NoSuchElementException 若迭代已經到頭,則 hasNext()爲false
*/
public T next();
/**
* Task:從迭代器刪除next()返回的下一個元素
* 此後調用next()的行爲將與刪除前一樣
* Precondition:next()已被調用,remove()尚未被調用
* 數據集在迭代期間 除調用本方法外未被修改
* @throws IllegalStateException 若next()未被調用
* @throws UnsupportedOperationException 若迭代器不允許刪除
*/
public void remove();
}
獨立類迭代器實現:
import java.util.ArrayList;
import java.util.NoSuchElementException;
/**
* 獨立類迭代器
* @param <T>
*/
public class SeparateIterator<T> implements Iterator<T> {
private ArrayList<T> list;
private int nextPosition; //next()返回最近元素的位置
private boolean wasNextCalled; //需要刪除的
public SeparateIterator(ArrayList<T> arrayList) {
list=arrayList;
nextPosition=0; //用於跟蹤迭代到何處
wasNextCalled=false; //用於檢出是否首先調用了next()
}
@Override
public boolean hasNext() {
return nextPosition<list.size();
}
@Override
public T next() {
if(hasNext()) {
wasNextCalled = true; //設置爲true,remove()方法可以調用next()
nextPosition++;
return list.get(nextPosition-1); //由於先前移,故減一
}
else
throw new NoSuchElementException("Illegal call to next();"+"iterator is after end of list!");
}
@Override
public void remove() {
if(wasNextCalled){
list.remove(nextPosition);
nextPosition--;
wasNextCalled=false;
}
else
throw new IllegalStateException("Illegal call to remove();"+"next() was not called!");
}
}
測試:
注意調用SeparateIterator的構造函數將迭代器nameofGQT與線性表nameList連接起來。
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("Ned");
arrayList.add("John");
arrayList.add("Robb");
arrayList.add("Sansa");
arrayList.add("Arya");
arrayList.add("Bran");
for (String s:arrayList) { //輸出
System.out.println(s);
}
System.out.println();
Iterator<String> nameofGQT=new SeparateIterator<String>(arrayList); //調用SeparateIterator的構造函數把迭代器namwodGQT與arrayList連接在一起
// while (nameofGQT.hasNext())
// System.out.print(nameofGQT.next()+" "); //用於測試,否則會拋出NoSuchElementException異常
// System.out.println();
nameofGQT.next(); //The old wolf is gone! Poor Ned!
// while (nameofGQT.hasNext())
// System.out.print(nameofGQT.next()+" "); //用於測試,否則會報出NoSuchElementException異常
// System.out.println();
nameofGQT.next();
nameofGQT.remove(); //The Young Wolf is dead!
//nameofGQT.remove(); //出錯,未先使用next(),報出IllegalStateException異常
while (nameofGQT.hasNext())
System.out.print(nameofGQT.next()+" ");
}
}