This post will implement the Iterable interface on a Java class holding a collection of objects to iterate over the collection using the for-each loop.

1. Implementing the Iterator Interface

Before we implement the Iterable interface, first, let’s see what we’ll get by only implementing the Iterator interface on a class holding a collection of objects.

Download  Run Code

Output:

1
2
3

 
We can’t use for-each loop here to iterate over the collection since the Collection class didn’t implement the java.util.Iterable interface. The Collection class object can access the Iterator though since Collection class implements the java.util.Iterator interface.

2. Implementing the Iterable Interface

Now let’s make the Collection class implement the java.util.Iterable interface, enabling it to work with for-each loops. Now we can iterate through the array of objects stored in the Collection class using both Iterator and for-each loop, as shown below:

Download  Run Code

Output:

1
2
3
1
2
3

That’s all about making the Iterable Interface work with for each loop.