Iterable<E>
is in java.lang
whereas Iterator<E>
is in java.util
. Is there a good reason for this or is this merely an artifact of bad design?
It seems strange since the only thing that an Iterable<E>
is good for is providing an Iterator<E>
.
EDIT: One potential reason is because of the (then-)newly introduced for-each loop. I guess my question then would be, are they equivalent?
for(Object o : collection)
...
vs
for( Iterator iter = collection.iterator(); iter.hasNext(); ) {
o = iter.next();
...
If they are, then that still doesn't explain why the two classes are in different packages since the compiler would have to import java.util
anyways to use the Iterator
construct.
Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object.
Implementing Iterable interface allows an object to be the target of the "foreach" statement. Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
This interface allows us to retrieve or remove elements from a collection during the iteration. In addition, it has two methods that help iterate over the data structure and retrieve its elements – next() and hasNext(). Moreover, it has a remove() method, which removes the current element pointed to by the Iterator.
2. Any class that implements the Iterable interface needs to override the iterator() method provided by the Iterable interface. The iterator() method returns an Iterator , which then can be used to iterate over an object of that class.
Part of it is history: Iterator
has been with us since JDK 1.2, and Iterable
came with JDK 1.5. Iterable
came in with the enhanced for
loop.
Bad design? No, evolution. There's no all-knowing creator. As lessons are learned they're incorporated into the JDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With