今天學習了迭代器,老師對迭代器的兩個方法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的構造方法,從而實現了把一個對象傳遞到了另一個對象中的過程,也實現了在一個對象中操作另一個對象的功能,這一塊還需要多思考,有了更深入了理解之后,再過來記載下來
新聞熱點
疑難解答