Implement Java Iterator and Iterable in same class?

后端 未结 4 1662
终归单人心
终归单人心 2020-12-13 21:03

I am trying to understand Java Iterator and Iterable interfaces

I am writing this class

class MyClass implements Iterable&         


        
4条回答
  •  有刺的猬
    2020-12-13 21:34

    I suppose this is a standard way to implement the Iterable and Iterator at the same time.

    // return list of neighbors of v
    public Iterable adj(int v) {
        return new AdjIterator(v);
    }
    
    // support iteration over graph vertices
    private class AdjIterator implements Iterator, Iterable {
        private int v;
        private int w = 0;
    
        AdjIterator(int v) {
            this.v = v;
        }
    
        public Iterator iterator() {
            return this;
        }
    
        public boolean hasNext() {
            while (w < V) {
                if (adj[v][w]) return true;
                w++;
            }
            return false;
        }
    
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return w++;
        }
    

    Reference https://algs4.cs.princeton.edu/41graph/AdjMatrixGraph.java.html.

提交回复
热议问题