Reputation: 421
I have an object that I would like to implement custom iteration into, but:
Iterator
object for all the actual iteration, because the iteration requires accessing a private field.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
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