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.
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.
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.
I'm somewhat confused about difference between Iterator and Iterable
Is my understanding of Iterators and Iterable correct?
In over my own head with linked lists, iterator and iterable
You should debug, this is a perfect opportunity to learn to. It's easy and fundamental
More on reddit.comI'm somewhat confused about difference between Iterator and ...
so I know how to implement (e.g public Iterator<E> iterator() { return new ListIterator<E>(//could add first element here); }
but sometimes I see it saying public iterable. what's the difference? I think it is iterator is like you go through it once and you're done but iterable you get back a list that you can go through over and over again?
if it helps the thing I'm having trouble about is this: http://coursera.cs.princeton.edu/algs4/assignments/8puzzle.html
public Iterable<Board> neighbors()
do I just have to return a linked list of some sort (stack/queue)? why not use iterator<Board> instead?
Edit: I got it, you're returning an object that is iterable itself.
Hi,
According to my understanding of Iterator and Iterable:
-
Iterableis used when you want to get for - each for a collection.Iteratoris still used behind the scenes to fetch the items for for-each. -
If I just want to go through a collection ( don't want for-each) , I can just implement Iterator interface on collection class and it should work. Note -
Iterableis not necessary. -
If I implement
Iteratorinterface on a collection class, It gives me the ability to iterate over the collection . Now if I implement the 'for-each' method (defined inIterableInterface ) in the class , then I can get a for-each loop for the collection , even without implementingIterable.
is it correct?
Thanks