Reputation: 463
When would it be useful to implement iterator without implementing iterable?
Or is implementing iterator simply a by product of implementing iterable?
Upvotes: 3
Views: 220
Reputation: 61128
These two are related but not the same.
A List
is Iterable
- you can get its Iterator
. It is not an Iterator
.
An Iterator
is a single use class that can iterate along a Collection
of objects using the hasNext
and next
methods.
An Iterable
is a Collection
class that returns an Iterator
instance when then the iterator()
method is called.
I would go as far as to say that I see no case where an Iterable
should implements Iterator
. And as a Iterator
is single use I cannot see a case where Iterator
should implements Iterable
.
Upvotes: 4
Reputation: 16392
Generally speaking, you'd implement either an Iterable or an Iterator to hide the implementation of a collection from the code that's iterating over the collection. Either one would work well. The difference lies in how many times the collection can be traversed. An iterator can only traverse the collection once while the Iterable can traverse the collection many times. You can traverse the Iterable by asking it for an Iterator and you can do that multiple times.
Upvotes: 1
Reputation: 16476
They are very similar in semantics and use cases, but differ in implementation. Iterable is a simple factory for Iterators which can be used inside for loops. For this reason it's might be more convenient to implement an Iterable.
for(String s : getIterable()){
...
}
Versus:
Iterator<String> it = getIterator();
while(it.hasNext()){
String s = it.next();
...
}
However, in some case Iterator might not be re-instantiated, i.e. when you're running through a db request results, so in this case you can't make it Iterable without re-sending your request.
Upvotes: 0