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

15

256

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

Roney answered 28/7, 2011 at 17:35 Comment(1)
Iterable<Integer> iterable = () -> list.iterator(); and Iterator<Integer> iterator = iterable.iterator();Penult
D
271

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.

Dirndl answered 28/7, 2011 at 17:41 Comment(1)
will that matter if Iterable has interal or external iterator or it is possible to have any of them ?Kolivas
F
101

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.

Facelifting answered 28/7, 2011 at 17:43 Comment(0)
A
32

I will answer the question especially about ArrayList as an example in order to help you understand better..

  1. Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable {
  ...
  abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T.
  ...
}
  1. Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator {
  ...
  abstract boolean hasNext(); //Returns true if the iteration has more elements.
  abstract E next();          //Returns the next element in the iteration.
  ...
}
  1. ArrayList implements List, List extends Collection and Collection extends Iterable.. That is, you could see the relationship like

    'Iterable <- Collection <- List <- ArrayList'

. And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.

  1. I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.

'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.

public class ArrayList<E> ... implements List<E>, ...
{
  ...
  public Iterator<E> iterator() {
              return new Itr();
  }


  private class Itr implements Iterator<E> {
          ...

          public boolean hasNext() {
              return cursor != size;
          }
          @SuppressWarnings("unchecked")
          public E next() {
              checkForComodification();
              int i = cursor;
              if (i >= size)
                  throw new NoSuchElementException();
              Object[] elementData = ArrayList.this.elementData;
              if (i >= elementData.length)
                  throw new ConcurrentModificationException();
              cursor = i + 1;
              return (E) elementData[lastRet = i];
          }
          ...
  }
}
  1. Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).

Here is a simple example.

public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String string = iterator.next();
        System.out.println(string);
    }
}

Now, is it clear? :)

Ardeha answered 8/12, 2017 at 1:50 Comment(1)
I Understood this post, but what if I want to write a method whose return type is Iterable<T> then in this scenario what steps do we need to implement? Please suggest that example also.Columbium
Z
29

I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:

Think of a public library. Old school. With paper books. Yes, that kind of library.

A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.

The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".

I know it's a bit silly, but I hope this helps.

Zamarripa answered 1/7, 2020 at 16:23 Comment(1)
very good example.. So cant we say... shelf of books is the thing and to go over it we have librarian. without librarian bookshelf has no value as we cant iterate over themWhist
A
16

If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.

Apposite answered 28/7, 2011 at 17:39 Comment(3)
FYI a java.util.Collection always implements java.util.Iterable.Tartarean
Is it not java.lang.Iterable ?Incense
It's java.lang.IterableInternationalist
B
9

Implementing Iterable interface allows an object to be the target of the "foreach" statement.

class SomeClass implements Iterable<String> {}

class Main 
{
  public void method()
  {
     SomeClass someClass = new SomeClass();
     .....

    for(String s : someClass) {
     //do something
    }
  }
}

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

Brittani answered 7/7, 2014 at 13:30 Comment(5)
If any class is implementing Iterable it should have a Iterator() method in it right??? Correct me if I am wrong.Brewster
yes. It should have interface's unimplemented method. In this case it is Iterator.Corduroy
Thanks for an intelligent answer. I came here to double check my understanding of Iterable vs Iterator. You confirmed it. All the other answers talk about the structure, which I guess is fine, but doesn't answer the question of WHY I'd use one over the other.Rodrigues
For me, this is the best answer.Glandular
I wanted to know what is the benefit of For each loop for String s: someClass. Since someClass is java class object and s String ref. Under what cirsumstances one should go with such sort of implementations.Arst
E
9

The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.

Eelworm answered 27/8, 2014 at 3:37 Comment(1)
I was wondering why collection classes do not implement Iterator interface directly (instead of implementing Iterable and returning Iterator object). This answer made it clear that - in that case it wouldn't have been possible to traverse collection multiple times (and also simultaneously by multiple threads). This is very important answer.Pagoda
U
3

As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

Unmindful answered 14/11, 2017 at 5:27 Comment(0)
O
2

Consider an example having 10 apples. When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.

By implementing iterator, we can get any apple, apple in next boxes etc.

So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.

Olives answered 17/8, 2017 at 6:8 Comment(0)
F
1

Question:Difference between Iterable and Iterator?
Ans:

iterable: It is related to forEach loop
iterator: Is is related to Collection

The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection

Iterable present in java.ḷang package
Iterator present in java.util package

Contains only one method iterator()
Contains three method hasNext(), next(), remove()

Introduced in 1.5 version
Introduced in 1.2 version

Faille answered 28/4, 2017 at 20:2 Comment(0)
I
1

Basically speaking, both of them are very closely related to each other.

Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()

On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct. It has only one method named iterator() which comes from Iterator interface itself.

When a collection is iterable, then it can be iterated using an iterator.

For understanding visit these:

ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java

ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java

Ingrid answered 7/6, 2017 at 15:11 Comment(0)
S
1

Iterable were introduced to use in for each loop in java

public interface Collection<E> extends Iterable<E>  

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

Snitch answered 6/2, 2019 at 17:35 Comment(1)
Welcome to SO, you could always take the tour here, so that your answer would be more helpful and clean. In our case the question is asking for an explanation regarding the two classes, but your answer is quite confusing instead of clearing things out. Also try to keep a ref, while posting snippets from known/valid/certified sources, to make your answer more concrete.Leguminous
S
0

In addition to ColinD and Seeker answers.

In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.

Iterable

A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:

iterableElements.forEach (x -> System.out.println(x) );

Iterator

This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:

for (Iterator i = c.iterator(); i.hasNext(); ) {
       Element e = i.next();    //Get the element
       System.out.println(e);    //access or modify the element
}

Sources:

  1. Java Doc Iterable
  2. Java Doc Iterator
Stretcher answered 31/5, 2017 at 15:5 Comment(0)
P
0

An anonymous class easily converts an Iterator to an Iterable and lets you use the Iterable syntax (for loops, forEach()).

Example: consider an Iterator<T> it

for (T element : new Iterable<T>() {

    @Override
    public Iterator<T> iterator() {
        return it;
    }

}) {
    //do something with `T element`
}

Abstracted in a function

static <T> Iterable<T> toIterable(Iterator<T> it) {
    return new Iterable<T>() {

        @Override
        public Iterator<T> iterator() {
            return it;
        }

    };
}

Usage

for (T element: toIterable(it) {
...
}
Puce answered 28/1, 2022 at 7:29 Comment(0)
I
0

Most java interfaces ends with 'able'. examples are Iterable, Cloneable, Serializable, Runnable, etc. Therefore, Iterable is an interface that has an abstract method called iterator() which returns an Iterator object.

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

Iterator interface has abstract method 'hasNext()' and 'next()'.

public interface Iterator {
 abstract boolean hasNext();
 abstract E next();          
}

A clear use is a List which extends->Collections Interface->extends Iterable enter image description here

List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");

Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
    String string = it.next();
    System.out.println(string);
}
Islander answered 2/2, 2023 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.