MAO3J1m0Op
MAO3J1m0Op

Reputation: 421

Implementing Iterable vs implementing Iterator

I have an object that I would like to implement custom iteration into, but:

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?

Upvotes: 0

Views: 69

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198481

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.

Upvotes: 2

Related Questions