I am trying to understand Java Iterator and Iterable interfaces
I am writing this class
class MyClass implements Iterable&
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.