object – How to create a custom Iterator in Java?
object – How to create a custom Iterator in Java?
A minimal example would be to return an empty iterator, whose hasNext()
always returns false
and next()
will throw NoSuchElementException
.
public Iterator<Foo> iterator() {
return new Iterator<Foo>() {
public boolean hasNext() {
return false;
}
public Foo next() {
throw new NoSuchElementException();
}
};
}
Of course most iterators have states. For example you can iterate from 0
to the integer value the Foo
instance holds.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Foo implements Iterable<Foo> {
private final int value;
public Foo(final int value) {
this.value = value;
}
@Override
public Iterator<Foo> iterator() {
return new Iterator<Foo>() {
private Foo foo = new Foo(0);
@Override
public boolean hasNext() {
return foo.value < Foo.this.value;
}
@Override
public Foo next() {
if (!hasNext()) throw new NoSuchElementException();
Foo cur = foo;
foo = new Foo(cur.value+1);
return cur;
}
};
}
public static void main(String[] args) {
Foo foo = new Foo(10);
for (Foo f: foo) {
System.out.println(f.value);
}
}
}
object – How to create a custom Iterator in Java?
Also Read: object – How to create a custom Iterator in Java?