0

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 Iterator object 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?

3
  • 1
    An Iterator encapsulates some state, most notably for the hasNext() and next() calls. What happens if someone wants to loop over your object twice? Commented Sep 24, 2019 at 0:45
  • With my intentions, I want to require them to make a new object to iterate again. Commented Sep 24, 2019 at 0:48
  • 2
    Did you know that member classes (including inner classes) can access private fields of the containing class? You can make an inner class that implements Iterator; you don't need to make your private field public for that. Commented Sep 24, 2019 at 1:19

1 Answer 1

2

This is not okay practice. Create a secondary Iterator object, and make that Iterator a nested class inside your current class, which will permit it to access private fields.

In general, trying to make your object an Iterable and an Iterator at the same time is extremely likely to confuse users and break code that makes assumptions about how an Iterable works, in particular that it can be used more than once.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.