java 迭代器原理初探

來源:互聯網
上載者:User

標籤:

今天學習了迭代器,老師對迭代器的兩個方法hasNext()和Next(),做了深入的理解,並且舉了一個簡單的例子大致類比了底層的實現,下面我來記錄下實現的過程,首先建立了一個

Collection.java 這是類比的Collection介面 代碼如下:

package cn.itcast.studyIterator;

public interface Collection {
    public Object get(int index);
    public int size();
    public Interator interator();
}

實作類別的代碼如下:

public class CollectionImal implements Collection {

    private String[] str = {"java","php","csharp","admin"};
            
    public Object get(int index) {
        return str[index];
    }

    public int size() {
        // TODO Auto-generated method stub
        return str.length;
    }

    public Interator interator() {
        // TODO Auto-generated method stub
        return new InteratorImpl(this);
    }

}

類比Iterator的介面代碼如下,只是定義了兩個簡單的功能:

package cn.itcast.studyIterator;

public interface Interator {
    public boolean hasNext();
    public Object next();
    
}

實現代碼如下:

public class InteratorImpl implements Interator {
    private Collection collection;
    private int index = -1;
    public InteratorImpl(Collection collection){
        this.collection = collection;
    }
    public boolean hasNext() {
        if(index < collection.size() - 1){
            return true;
        }
        return false;
    }
    public Object next() {
        index++;
        return collection.get(index);
    }

}

最後就是調用代碼了:

public class Test {
    public static void main(String[] args) {
        CollectionImal collection = new CollectionImal();
        Interator it = collection.interator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        
    }
}

我感覺這個過程的關鍵就是兩個類之間的資料傳遞,CollectionImal類的成員方法interator方法,將自己傳遞給了InteratorImpl的構造方法,從而實現了把一個對象傳遞到了另一個對象中的過程,也實現了在一個對象中操作另一個對象的功能,這一塊還需要多思考,有了更深入了理解之後,再過來記載下來

 

java 迭代器原理初探

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.