Implement the Iterable Interface to work with for-each loops

In this post, we will implement the Iterable interface on a 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 lets 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 Collection class didn’t implement the java.util.Iterable interface. Collection class object can access the Iterator though since Collection class implements the java.util.Iterator interface.

 

2. Implementing the Iterable interface

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

 

Download   Run Code

Output:

1
2
3
1
2
3

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz