Java Iterator

import java.util.Iterator;
import java.util.NoSuchElementException;

/*重新定义Iterator时,需要重载hasNext(),以及next()函数
*/
public class OHIterator implements Iterator<OHRequest> {
    OHRequest curr;

    public OHIterator(OHRequest original) {
        curr = original;
    }

    public boolean isGood(String description) {
        return description != null && description.length() > 5;
    }
    
    @Override
    public boolean  hasNext() {
        /*if(curr == null) return false;
        */
        while(curr!= null && !isGood(curr.description)) {
            curr = curr.next;
        }
        
        return curr != null;

    }
    
    public OHRequest next() {
        if(!hasNext()) {
            throw new NoSuchElementException();
        }
        
        OHRequest currRequest = curr;
        curr = curr.next;
        return currRequest;
    }
}

2.新的迭代器 的接口为Iterator类

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

3.想让自己定义的类支持Foreach循环,需要继承Interable类

import java.util.Iterator;
import java.util.NoSuchElementException;
//继承Iterable, 为了支持foreach循环
public class OfficeHourQueue implements Iterable<OHRequest> {
    
    OHRequest queue;

    public OfficeHourQueue(OHRequest queue) {
        this.queue = queue;
    }
    
    @Override
    public Iterator<OHRequest> iterator() {
        return new OHIterator(queue);
    }

    public static void main(String[] args) {
        OHRequest s1 = new OHRequest("Failing my test for get in arrayDeque, NPE", "Pam", null);
        OHRequest s2 = new OHRequest("conceptual: what is dynamic method selection", "Michael", s1);
        OHRequest s3 = new OHRequest("git: what does checkout do.", "Jim", s2);
        OHRequest s4 = new OHRequest("help", "Dwight", s3);
        OHRequest s5 = new OHRequest("debugging get(i)", "Creed", s4 );
        OfficeHourQueue q = new OfficeHourQueue(s5);

        for(OHRequest o : q) {
            System.out.println(o.name);

        }
    }


    
}

 

posted @ 2019-04-03 21:06  卷积  阅读(292)  评论(0编辑  收藏  举报