Reputation: 17746
I've this problem:
Given the iterable
class Foo
, which keeps always only oneint
value which is set on its constructor, make an iterator so it respects all of its restrictions which are: you can't change theint
value after its initialization. You should include only the required exceptions to be thrown.
Ok, so far, if I understood the question the right way, I should create an iterator for that Foo
class, however I've never done this before and it seems to be that the question itself is a bit misleading. Is it a list? Or shouldn't it be? Anyway, despite that, all I want to know is how to create it.
So now I've this:
public class Foo implements Iterable<Foo> {
@Override
public Iterator<Foo> iterator() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
But I don't even know if this is the right way to do so. I'd be very appreciated if someone could help me out with this.
Thank you in advance.
Upvotes: 3
Views: 11640
Reputation: 8587
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);
}
}
}
Upvotes: 3