I have an object that I would like to implement custom iteration into, but:
- I do not want to have to create all of the next patterns at once.
- I want it to work in the enhanced for-loops, but I do not want to have to create a secondary
Iteratorobject for all the actual iteration, because the iteration requires accessing a private field. - I want to require a second object being made rather than a second iterator be made.
So my solution was to implement both Iterator and Iterable, and include the following method in my implementation:
@Override
public java.util.Iterator iterator() {
return this;
}
Is this okay practice? If it isn't, what should I do to properly work around this problem?
Iteratorencapsulates some state, most notably for thehasNext()andnext()calls. What happens if someone wants to loop over your object twice?