Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Iterable<E> and Iterator<E> in different packages?

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.

like image 314
tskuzzy Avatar asked Aug 02 '11 01:08

tskuzzy


People also ask

What is the difference between an iterator and an iterable?

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.

What is the difference between the Iterable interface and the iterator interface?

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.

What is the purpose of the Iterable interface What about 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.

Can you implement Iterable without 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.


1 Answers

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.

like image 85
duffymo Avatar answered Nov 15 '22 14:11

duffymo