I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?
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).
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.
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.
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 Iterator
s.
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.
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