国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java中迭代器初深

2019-11-14 15:16:08
字體:
來源:轉載
供稿:網友

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 天门市| 新沂市| 牡丹江市| 凭祥市| 商水县| 衡阳县| 确山县| 阿克苏市| 浦县| 江阴市| 沂水县| 西贡区| 普洱| 东安县| 扶沟县| 苍溪县| 岑巩县| 永寿县| 卓尼县| 柳江县| 菏泽市| 木里| 洮南市| 绿春县| 精河县| 清镇市| 泾阳县| 关岭| 莫力| 铜鼓县| 蕲春县| 长沙县| 吴川市| 太康县| 五寨县| 屏边| 榆树市| 崇信县| 观塘区| 霍林郭勒市| 永仁县|