Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between iterator and iterable and how to use them?

I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?

like image 941
Charles Cai Avatar asked Jul 28 '11 17:07

Charles Cai


People also ask

What is the difference between an iterator and an Iterable?

An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable).

How do I use an iterator in python?

Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable.

When would you use an iterator?

Iterator in Java is used to traverse each and every element in the collection. Using it, traverse, obtain each element or you can even remove. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.


2 Answers

An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a "current element". Instead, it has one method that produces an Iterator.

An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element (if any) using next().

Typically, an Iterable should be able to produce any number of valid Iterators.

like image 68
ColinD Avatar answered Sep 28 '22 04:09

ColinD


An implementation of Iterable is one that provides an Iterator of itself:

public interface Iterable<T> {     Iterator<T> iterator(); } 

An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).

public interface Iterator<E> {     boolean hasNext();     E next();     void remove(); } 

See Javadoc.

like image 40
Keith Pinson Avatar answered Sep 28 '22 05:09

Keith Pinson