標籤:override public this null size class return test i++
迭代器模式:用來迭代一個容器集合數組的一種模式。可能大家很多時候是用for迴圈進行迭代的,但是實際上for迴圈內部不能使用remove方法,但是迭代器可以,這是因為迭代器內部進行了該方法的邏輯處理。同樣我們也可以用到迭代器模式去迭代,他很好的封裝了迭代方法。我們還可以從中進行一些特特異的迭代選取功能,比如迭代數位字串但是返回尾數為13579的數字for迴圈內部的東西可以封裝在迭代器中。代碼如下
public class Test2 { @Test public void t() { CollectionA ca=new CollectionA(); String[] s={"我","了","個","去"}; ca.buildCollectionA(s); while(ca.hasNext()){ System.out.println(ca.next()); } }}//迭代器介面interface Iterator{ //如果有下一個就表示為true,如果沒有下一個就表示為false public boolean hasNext(); //取得當前迭代值並且把迭代標記推送到下一個上 public Object next();}//迭代器class CollectionA implements Iterator { //當前下標標記 private int i=0; //迭代的內容 private String[] obj; public void buildCollectionA(String[] s){ this.obj=s; } @Override public boolean hasNext() { if(i>=obj.length){ return false; } return true; } @Override public Object next() { if(hasNext()){ return obj[i++]; } return null; }}
迭代器模式(think in java中的設計模式)